Random access to my data


#1

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 :slight_smile:

Thanks in advance


Krzysztof R±czkiewicz