Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the difference between "__send__" and "instance_variable_get / instance_variable_set" methods?
    text
    copied!<p>All is stated in the question. Both of these methods can access (read/write) instance variables by using their code name :</p> <pre><code>__send__ instance_variable_set instance_variable_get </code></pre> <p>Could someone explain it by examples ?</p> <p>Metaprogramming is sometimes melting our brain when we explore it with abstraction.</p> <p>=== EDIT ===</p> <p>Ok I make a resume of the answers as an example for later use if my brain is melting again.</p> <p><strong>Class declaration</strong> :</p> <pre><code>class Person attr_accessor :first_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end def full_name @first_name + ' ' + @last_name end end </code></pre> <p><strong>Initialization</strong> :</p> <pre><code>actor = Person.new('Donald', "Duck") =&gt; #&lt;Person:0xa245554 @first_name="Donald", @last_name="Duck"&gt; </code></pre> <p><strong>usage of send</strong> (read) :</p> <pre><code>actor.send('first_name') =&gt; "Donald" actor.send(:first_name) =&gt; "Donald" actor.send("last_name") =&gt; "Duck" actor.send(:last_name) =&gt; "Duck" actor.send('full_name') =&gt; "Donald Duck" actor.send(:full_name) =&gt; "Donald Duck" </code></pre> <p><strong>usage of instance_variable_get</strong> (read)</p> <pre><code>actor.instance_variable_get('@first_name') =&gt; "Donald" actor.instance_variable_get(:@first_name) =&gt; "Donald" actor.instance_variable_get('@last_name') =&gt; "Duck" actor.instance_variable_get(:@last_name) =&gt; "Duck" </code></pre> <p><strong>usage of send</strong> (write) :</p> <pre><code>actor.send('first_name=', 'Daisy') actor.send('full_name') =&gt; "Daisy Duck" actor.send(:first_name=, "Fifi") actor.send("full_name") =&gt; "Fifi Duck" </code></pre> <p><strong>usage of instance_variable_set</strong> (write)</p> <pre><code>actor.instance_variable_set('@first_name', 'Pluto') actor.send("full_name") =&gt; "Pluto Duck" actor.instance_variable_set(:@last_name, 'Dog') actor.send(:full_name) =&gt; "Pluto Dog" </code></pre> <p><strong>INCORRECT usage of instance_variable_get</strong> (read)</p> <pre><code>actor.instance_variable_get('full_name') #NameError: `full_name' is not allowed as an instance variable name actor.instance_variable_get('last_name') #NameError: `last_name' is not allowed as an instance variable name </code></pre> <p>I was geting confuse with Rails ActiveRecord and its Associations.</p> <p>Thanks for the answers !</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