Forum: Ruby on Rails random access to my data

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
punkracy (Guest)
on 2007-01-27 03:35
(Received via mailing list)
Hi, I have an algorithmic problem, and also problem with writing my
idea's in Ruby Way.

I have model Section which keeps info about sections like (history,
mathematic, biology etc.). I also have model with Question for
questions appropriate to one category. I set correct relations between
them (has_many, belongs_to), so I can get questions from first by:
Section.find(:first).questions (I know it's an array*)

code:

<% for section in @sections %>
 Section: <%= section.name %>
 <% for question in section.questions %>
   Question: <%= question.id %> - <%= question.body %>
 <% end %>
<% end %>

will give me something like:
Section: History
Question: 2 - Lorem ipsum a
Question: 3 - Lorem ipsum b
Question: 7 - Lorem ipsum c
Question: 12 - Lorem ipsum d

Section: Biology
Question: 4 - Lorem ipsum x
Question: 6 - Lorem ipsum y
Question: 8 - Lorem ipsum z
Question: 9 - Lorem ipsum w


Now I want to generate collection of random and unique questions from
every category. Something like:
Question: 3 - Lorem ipsum b
Question: 7 - Lorem ipsum c
Question: 4 - Lorem ipsum x
Question: 9 - Lorem ipsum w

*Using array, it would be something like (but should I do it this
way?):
a = Array.new(10)
b = Array.new(7)
a.fill {|i| i}
r1 = 0..6
r1.each do |j|
 i = rand(10-j)
 x = a[i]
 b[j] = x
 a.delete_at(i)
end

Please give me some advice to write it with Rails in Ruby way :)

Thanks in advance

--
Krzysztof R┬▒czkiewicz
This topic is locked and can not be replied to.