Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are 3 cases here which could be relevant:</p> <ul> <li>Instance variable of the definer of the block that references the instance variable (in the example the usage of <code>awesome2</code>.</li> <li>Instance variable of the definer of the block that gives the instance variable as argument to the receiver (no chance to give it as argument to the block). This is usage of <code>awesome</code>.</li> <li>Instance variable of the user of the block that gives the instance variable as argument to the block. This is usage of <code>awesome3</code>.</li> </ul> <p>So lets try to implement both examples to see them. The example is lengthy, the relevant lines are:</p> <ul> <li><code>awesome</code> gets the instance variable as argument, which is then used by the receiver in the call of the block</li> <li><code>awesome2</code> gets no instance variable, it is bound by <code>Sender#use_in_block</code>. No chance for the receiver to change that binding.</li> <li><code>awesome3</code> gets the instance variable of the sender, but uses its own instance variable for calling the block</li> </ul> <p>So depending on what you want to reach, one of the three is the better solution.</p> <pre><code>class Sender attr_accessor :send_var def call_a_block(var) rec = Receiver.new(5) @my_var = var res = rec.awesome(@my_var) do |arg1| arg1 + 3 end res2 = rec.awesome3(@my_var) do |arg1| arg1 + 3 end p "Result of calling awesome with: 3 and #{@my_var} is #{res}" p "Result of calling awesome3 with: 3 and #{@my_var} is #{res2}" end def use_in_block(var) rec = Receiver.new(6) @my_var = var res = rec.awesome2 do 4 + @my_var end p "Result of calling awesome2 with: 4 and #{@my_var} is #{res}" end end class Receiver attr_accessor :rec_var def initialize(var) @rec_var = var end def awesome(arg1) res = yield(arg1) res * 2 end def awesome3(arg1) res = yield(@rec_var) res * 2 end def awesome2 res = yield res * 2 end end s = Sender.new s.call_a_block(7) s.call_a_block(20) s.use_in_block(7) s.use_in_block(20) </code></pre> <p>Results are:</p> <pre><code>c:\Temp&gt;ruby call.rb "Result of calling awesome with: 3 and 7 is 20" "Result of calling awesome3 with: 3 and 7 is 16" "Result of calling awesome with: 3 and 20 is 46" "Result of calling awesome3 with: 3 and 20 is 16" "Result of calling awesome2 with: 4 and 7 is 22" "Result of calling awesome2 with: 4 and 20 is 48" </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