0

I know the title is ridiculously long, but I'm in need of some assistance with Ruby on Rails and Sqlite3.

I had originally thought doing something like 4.times { (0..??).to_a.shuffle } would print a number between 0 and ?? (e.g. 20) four times, but all it did for me (in the rails console) was print the number '4' once.

Any idea on how I can do this successfully in Ruby on Rails by accessing a database table called "bullets" and using embedded ruby (.erb)?

Evan
  • 345
  • 1
  • 5
  • 14

2 Answers2

2

You can pull 4 random rows from sqlite using a query like:

select * from bullets order by random() limit 4;

So the AREL syntax is:

Bullet.select(:id).order('random()').limit(4).collect { |b| b.id }
=> [24, 6, 57, 37] 
Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
  • Thank you so much. I changed :id and b.id to :content and b.content to display what I should have asked for instead of not clarifying the tables. Out of curiosity is there a way to do this with one random row four different times each displaying something random on the list with no two "bullets" having the same data? – Evan Jun 25 '12 at 02:08
0

If you are looking to for an array of random numbers from 0 to n, try:

4.times.collect {rand(20)}
nickgroenke
  • 1,472
  • 9
  • 12