method
of_caller

v1.1.6 -
Show latest stable
-
0 notes -
Class: Binding
- 1.0.0 (0)
- 1.1.6 (0)
- 1.2.6 (-38)
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
of_caller(&block)
public
This method returns the binding of the method that called your method. It will raise an Exception when you’re not inside a method.
It’s used like this:
def inc_counter(amount = 1) Binding.of_caller do |binding| # Create a lambda that will increase the variable 'counter' # in the caller of this method when called. inc = eval("lambda { |arg| counter += arg }", binding) # We can refer to amount from inside this block safely. inc.call(amount) end # No other statements can go here. Put them inside the block. end counter = 0 2.times { inc_counter } counter # => 2
Binding.of_caller must be the last statement in the method. This means that you will have to put everything you want to do after the call to Binding.of_caller into the block of it. This should be no problem however, because Ruby has closures. If you don’t do this an Exception will be raised. Because of the way that Binding.of_caller is implemented it has to be done this way.