R. Avila R. Avila - 7 months ago 26
Ruby Question

What does this code in ruby do?

I am new here so please be gentle with me and I'm still just a newbie in programming and especially in ruby language.

This is a combo box and I want to know where it goes after I change it or what function it calls. Can you please tell me where it goes or what it does? thanks

<p><%= f.select :done_ratio, ((0..100).step(1).to_a.collect {|r| ["#{r} %", r] }), :required => @issue.required_attribute?('done_ratio') %></p>

Answer Source

It is creating an HTML select (dropdown) box, with the values: 0 %, 1 %, 2 %, ..., 100 %.

The field will be submitted as part of a form. It may or may not be a required field, depending on the value of @issue.required_attribute?('done_ratio'). (This is presumably a method in the Issue model, which can be found in ./app/models/issue.rb.)

Breaking it down:

  • (0..100) -- This is creating Range object, from 0 to 100 (inclusive).
  • .step(1) -- This is not actually needed; you could delete it. But it's saying "step through the range 1 at a time" (which is the default anyway). It converts the Range to an Enumerator.
  • .to_a -- This is not actually needed; you could delete it. This is converting the Enumerator to an Array.
  • .collect {|r| ["#{r} %", r] } -- This is mapping the Array to a new list of arrays, like: [["0 %", 0], ["1 %", 1], ..., ["100 %", 100]]. (This method would also work perfectly fine on a Range or Enumerator object, since both classes include this method from the Enumerable module. Hence why the above two steps can both be removed!)
  • f.select :done_ratio, (...) -- This is creating an HTML select element called done_ratio, with the above names/values.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download