Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Actually <code>severin</code> have a better idea, just because usage of method_missing is a bad practice, not all the time, but most of it.</p> <p>One problem with that code provided by <code>severin</code>: it returns value that have been passed to initializer, so you cannot change it. I suggest you a little different approach:</p> <pre><code>class User &lt; Hash def initialize(attrs) attrs.each do |k, v| self[k] = v end end def []=(k, v) unless respond_to?(k) self.class.send :define_method, k do self[k] end end super end end </code></pre> <p>Lets check it:</p> <pre><code>u = User.new(:name =&gt; 'John') p u.name u[:name] = 'Maria' p u.name </code></pre> <p>And also you can do it with Struct:</p> <pre><code>attrs = {:name =&gt; 'John', :age =&gt; 22, :position =&gt; 'developer'} keys = attrs.keys user = Struct.new(*keys).new(*keys.map { |k| attrs[k] }) </code></pre> <p>Lets test it:</p> <pre><code>p user p user.name user[:name] = 'Maria' p user.name user.name = 'Vlad' p user[:name] </code></pre> <p>Or even OpenStruct, but be careful it will not create method if it already have it in instance methods, you can look for that by using <code>OpenStruct.instance_methods</code> (because of type is used, I'm now using second approach):</p> <pre><code>attrs = {:name =&gt; 'John', :age =&gt; 22, :position =&gt; 'developer'} user = OpenStruct.new(attrs) </code></pre> <p>Yep, so easy:</p> <pre><code>user.name user[:name] # will give you an error, because OpenStruct isn't a Enumerable or Hash </code></pre>
 

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