简体   繁体   中英

Using loop count to modify variable name in ruby

I would like to have review.avg_answer2, review.avg_answer3, etc outputted by the following loop:

  <% @count = 1 %>
  <% 10.times do |x| %>
    <td><%= link_to review.avg_answer1.to_i, "#" %></td>
    <% @count += 1 %>
  <% end %>   

I know there is a simple answer, but it's not hitting me.

I tried "review.avg_answer#{@count}.to_i" but of course it doesn't work.

Thanks!

它行得通吗?

review.send("avg_answer#{@count}").to_i

This should work for you case..
10.times.each {|x| review.send("avg_answer#{x}")} OR 10.times.each {|x| review.send("avg_answer#{x}")} OR 10.times.each {|x| review.send(:"avg_answer#{x}")}`

If you envision to pass Params to your method then you can vary it by: 10.times.each {|x| review.send("avg_answer#{x}",params1,params2)} 10.times.each {|x| review.send("avg_answer#{x}",params1,params2)} OR 10.times.each {|x| review.send(:"avg_answer#{x}",params1,params2)} 10.times.each {|x| review.send(:"avg_answer#{x}",params1,params2)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM