My template looks like:
<h2>Oracle</h2>
<% @q_oracle.each do |q| %>
<%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s, 'http://stackoverflow.com/' + q.question_answers_url) %> </br>
<% end %>
<h2>Ruby and Rails</h2>
<% @q_ruby.each do |q| %>
<%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s, 'http://stackoverflow.com/' + q.question_answers_url) %> </br>
<% end %>
So the temlate consists the static titles (h2) and loops through the array. I am searching the way to avoid copy-paste code in the my template. Something like:
@hash = { 'Oracle' => @q_oracle, 'Ruby and Rails' => @q_ruby }
@hash.each { |@t, @a|
<h2>@t</h2>
<% @a.each do |q| %>
<%= link_to(q.title + ' (' + q.answer_count.to_s + ') ' + q.question_id.to_s, 'http://stackoverflow.com/' + q.question_answers_url) %> </br>
<% end %>
}
Is it possible?
Yes you can do it.
Ruby 1.9 solution
In Ruby 1.8 this solution can be used when titles order doesn’t matter. In Ruby 1.9 titles would appear in order they were inserted in hash.
Just place this variable to your controller action:
And access this variable from your view:
Ruby 1.8 with sorted keys
This method sorts keys so they appear in alphabetical order.
Ruby 1.8 with arrays
This method would behave like Ruby 1.9 in any ruby version – titles would appear in order they were added.
Variable
@hashmust be initialized as:View must be updated to: