Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can try to use <a href="http://www.ruby-doc.org/stdlib-1.9.3/libdoc/ostruct/rdoc/OpenStruct.html" rel="nofollow">OpenStruct</a> for this.</p> <blockquote> <p>An OpenStruct is a data structure, similar to a Hash, that allows the definition of arbitrary attributes with their accompanying values. This is accomplished by using Ruby’s metaprogramming to define methods on the class itself.</p> </blockquote> <pre><code>require 'ostruct' (0..10).map { |i| OpenStruct.new(:id =&gt; i*10, :name =&gt; "#{i*10}%") } # =&gt; [#&lt;OpenStruct id=0, name="0%"&gt;, #&lt;OpenStruct id=10, name="10%"&gt;, ... </code></pre> <p>But if you need a real class, not anonymous class like OpenStruct, then just create this class instances inside the collect/map method:</p> <pre><code>class Ratio attr_reader :id, :name def initialize(id, name) @id = id; @name = name end end (0..10).map { |i| ratio = i*10; Ratio.new(ratio, "#{ratio}%") } # =&gt; [#&lt;Ratio: @id=0, @name="0%"&gt;, #&lt;Ratio: @id=10, @name="10%"&gt;, ... </code></pre> <hr> <p>Maybe I misunderstood you a bit and you want to create this structure not from range, but from array <code>[["0 %", 0], ["10 %", 10], ["20 %", 20], ["30 %", 30]]</code> then the code is similar:</p> <pre><code>require 'ostruct' arr = [["0 %", 0], ["10 %", 10], ["20 %", 20], ["30 %", 30]] p arr.map { |name, id| OpenStruct.new(:id =&gt; id, :name =&gt; name) } # =&gt; [#&lt;OpenStruct id=0, name="0 %"&gt;, #&lt;OpenStruct id=10, name="10 %"&gt;, #&lt;OpenStruct id=20, name="20 %"&gt;, #&lt;OpenStruct id=30, name="30 %"&gt;] </code></pre> <hr> <p><strong>UPDATE</strong> I found one corner case in usage of OpenStruct (looks like this is the case for <strong>Ruby 1.8.7</strong> only): <code>OpenStruct#id</code> will return <code>object_id</code> for <code>id</code> instead of field value: </p> <pre><code>ruby-1.8.7-p352 &gt; o = OpenStruct.new :id =&gt; 10 =&gt; #&lt;OpenStruct id=10&gt; ruby-1.8.7-p352 &gt; o.id (irb):4: warning: Object#id will be deprecated; use Object#object_id =&gt; 70021843187380 </code></pre> <p>There are two workarounds: </p> <pre><code># 1. redefine OpenStruct#id method: OpenStruct.__send__(:define_method, :id) { @table[:id] } # 2. dont use 'id' as a value and use any other value: require 'ostruct' (0..10).map { |i| OpenStruct.new(:value =&gt; i*10, :name =&gt; "#{i*10}%") } # 'value' instead of 'id' ... options_from_collection_for_select(@arr, 'value', 'name') </code></pre> <p>I recommend you to use second approach.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload