When I pass a lambda to instance_eval as the block, it seems to pass an extra argument:
lamb = -> { puts 'hi' }
proc = Proc.new { puts 'hi' }
instance_eval(&lamb)
# >> ArgumentError: wrong number of arguments (given 1, expected 0)
# from (irb):5:in `block in irb_binding'
# from (irb):7:in `instance_eval'
instance_eval(&proc)
# => hi
instance_exec(&lamb)
# => hi
Why is this the case? Note that this question is NOT about why lambda throws an error. That is well understood. The question is about WHY instance_eval sends self of the receiver as a parameter. It is not needed, and confusing. And AFAIK not documented.
This helps, but doesn't explain WHY ruby would do it this way. The whole point of instance_eval is to set self to the receiver; why confuse things by also passing self to the proc?
From the docs
For procs created using lambda or ->() an error is generated if the
wrong number of parameters are passed to a Proc with multiple
parameters. For procs created using Proc.new or Kernel.proc, extra
parameters are silently discarded.
In your case both lamb and proc called with one parameter
From the docs of instance_eval
When instance_eval is given a block, obj is also passed in as the
block's only argument
instance_eval is method of BasicObject class and can be called within instance. So given block will have access for private methods for example.
class Test
def call
secret_number + 100
end
private
def secret_number
42
end
end
test = Test.new
show_secret = -> (obj) { puts secret_number }
test.instance_eval(&show_secret) # print 42
Without instance self of current context will be passed as an argument. I think instance_eval was designed more for calling it within objects.
From the docs of instance_eval
In order to set the context, the variable self is set to obj while the
code is executing, giving the code access to obj's instance variables
and private methods.
Related
This article touches on the issues but doesn't give a solution.
This started when I wanted to write a method and optionally pass it an argument which could be null or a ???? (proc, lambda, method, block, ???). Lets call it, for now, a block because a block works. The block takes one required argument. An example of the method and a call to it would be:
#!/usr/bin/env ruby
def foo(&proc)
puts "before"
if proc
yield "passed to proc"
end
puts "after"
end
def add_message(s)
puts "from add_message #{s}"
end
foo { |s| add_message(s) }
foo
And the output is:
before
from add_message passed to proc
after
before
after
Great. But, what I'd like to do is be able to call foo like this: foo(&:add_message). But I can't. Changing line 15 above I get:
before
./temp.rb:11:in `add_message': wrong number of arguments (given 0, expected 1) (ArgumentError)
from ./temp.rb:6:in `foo'
from ./temp.rb:15:in `<main>'
And, as the article above mentions, the arity is now -2. So, how do I write a simple method like add_message that I can use with &:add_message. OR!!! as is the case 99.99% of the time, please set me on the proper track on how to do this.
The problem is that Symbol#to_proc does not create a proc that calls add_message method correctly.
# `yield` will pass its arguments to proc
>> :add_message.to_proc.call('passed to proc')
# => ArgumentError
This calls 'passed to proc'.add_message, because our method is defined in Object it works when called on String, however it is missing the required argument.
The solution is to make a proc that can accept the same arguments as add_message method and pass them along to that method. We can use Object#method that returns Method object that implements its own to_proc and has the same arity as the method.
>> method(:add_message).to_proc.arity
=> 1
>> method(:add_message).to_proc.call('passed to proc')
from add_message passed to proc
>> foo(&method(:add_message))
before
from add_message passed to proc
after
From the Ruby docs
Conversion of other objects to procs
Any object that implements the to_proc method can be converted into a proc by the & operator, and therefore can be consumed by iterators.
class Greeter
def initialize(greeting)
#greeting = greeting
end
def to_proc
proc {|name| "#{#greeting}, #{name}!" }
end
end
hi = Greeter.new("Hi")
hey = Greeter.new("Hey")
["Bob", "Jane"].map(&hi) #=> ["Hi, Bob!", "Hi, Jane!"]
["Bob", "Jane"].map(&hey) #=> ["Hey, Bob!", "Hey, Jane!"]
Of the Ruby core classes, this method is implemented by Symbol, Method, and Hash.
So when you pass an argument with a unary ampersand before it, to_proc gets called on it. The &: "syntax" is actually & being called on a symbol literal, i.e. &(:foobar), and Symbol.to_proc has the behavior of converting a symbol into a method call on its first argument, i.e. these two are roughly equivalent (modulo named argument forwarding)
:foobar.to_proc
proc { |x, *args| x.foobar(*args) }
Ruby's Method type also implements to_proc, so if you have a standalone method called foobar (on a module, say, Example), then you can call Example.method(:foobar) and get an &-compatible object. If you have a "top-level" method, then it's probably being defined on the main object and calling method with no explicit receiver will work.
The other type mentioned in that quote is hashes, which can be turned into a function mapping their keys to their values (and returning nil if no matching key exists). And, of course, you can always implement a method called to_proc on your own classes and it'll work just as well as any built-in type.
class Integer
def set
return self + 1
end
end
p [1,2,3,4,5,6].map(&:set)
I think when you can use &: syntax that a method have been defined for a class like above
I want to extend the functionality of a method asdf at runtime.
A method append_asdf should allow modifying the method more easily.
I understand how to call the previous method but the private variable #b evaluates to nil inside the block used to specify the additional behaviour - if passed through the wrapper.
It works as expected when passed to class_eval directly (which is not what I want).
Why?
class A
def initialize
#b = "144"
end
def asdf
puts "12"
end
def self.append_asdf(&n)
m = instance_method(:asdf)
define_method(:asdf) {
m.bind(self).call
n.call
}
end
end
a = A.new
p = proc {
puts #b
}
The proc p is used here to drive home the point that it doesn't depend on the block. It behaves the same as a literal.
This doesn't work:
A.append_asdf(&p)
a.asdf
=>
12
Note the empty line. The same proc used here evaluates as expected:
A.class_eval {
define_method(:asdf, p)
}
a.asdf
=>
144
You need to evaluate that block in the proper context. In other words:
instance_eval(&n)
Instead of a regular call.
I want to call a lambda changing it's self value. Searching for it, I arrived at instance_exec, which was supposed to get the job done.
However, after 1+ hour studying an example, I found this behavior I can't explain:
class Dummy
class << self
attr_accessor :my_lambda
end
self.my_lambda = proc { self }
def test
self.class.my_lambda.call
end
def test1
instance_eval(&self.class.my_lambda)
end
def test2
instance_eval { self.class.my_lambda.call }
end
end
Dummy.new.test
=> Dummy # I was expecting this, returns the class, lexical scope (where `self` was defined)
Dummy.new.test1
=> #<Dummy:0x00007fe982f8b678> # I was expecting this, `self` changed to the receiver of `instance_eval`, which is the instance, so `self` returned the instance.
Dummy.new.test2
=> Dummy # I can't understand this, at all. Why isn't it the same as test1?
So, why do we get different results from instance_eval(&self.class.my_lambda) vs instance_eval { self.class.my_lambda.call } ?
Also, since we're at the subject of calling Lambdas ... if I change the class level variable to this:
self.my_lambda = lambda { self }
then Dummy.new.test1 throws an exception ArgumentError: wrong number of arguments (given 1, expected 0), which I also can't understand why, since I know lambdas are strict about argument numbers, but we didn't pass any when we used instance_eval(&self.class.my_lambda)
Amazingly how, right away after writing this long question, I managed to answer it myself in one extra minute. I needed a rubber duck. Anyways.
I misunderstood instance_eval. It "Executes the given block within the context of the receiver (obj)."
So, the given block in #test2 instance_eval { self.class.my_lambda.call } was, indeed, executed with self set to the instance, but the lambda was still called within it, which doesn't change it's self.
However, in #test1, the ampersand & changed the proc to a block, and then it was passed to instance_eval, so it was the proc's own body that was executed with the self changed.
Looking at this instance_eval example:
class KlassWithSecret
def initialize
#secret = 99
end
def get
#secret
end
end
k = KlassWithSecret.new
k.instance_eval { #secret }
print k.get
I added a get method to KlassWithSecret.
Here's the results of running the program:
>ruby InstanceEvalTest.rb
99
So, does instance_eval here somehow call the initialize method?
I think that I understand this method a bit from reading this helpful post. But I'm still in the dark.
The initialize method is automatically called by Ruby after the new method is called. instance_eval runs the block you supply in the context of the object. This means it has access to anything a normal line of code in the KlassWithSecret class would have.
#secret is an instance variable, meaning that it belongs to an instance of KlassWithSecret. Because we're evaluating { #secret } in the context of a KlassWithSecret instance, we can access #secret.
k.instance_eval gives you access to all of the instance variables (here just #secret) and all private methods (if there were any). It executes the code in the block, which in this case returns 99, the value of #secret. Then print k.get prints that value and returns nil.
If the block had been { #secret = 'cat' }, k.instance_val would have changed the value of #secret (and returned the new value).
When using instance_eval, class_eval, class < self and other metaprogramming constructs, you mind find it helpful to track the value of self using puts statements. For example:
k = KlassWithSecret.new #=> #<KlassWithSecret:0x00000101897810 #secret=99>
self #=> main
k.instance_eval { puts "self=#{self}"; #secret }
"self=#<KlassWithSecret:0x00000101897810>"
#=> 99
Is it possible to convert a proc-flavored Proc into a lambda-flavored Proc?
Bit surprised that this doesn't work, at least in 1.9.2:
my_proc = proc {|x| x}
my_lambda = lambda &p
my_lambda.lambda? # => false!
This one was a bit tricky to track down. Looking at the docs for Proc#lambda? for 1.9, there's a fairly lengthy discussion about the difference between procs and lamdbas.
What it comes down to is that a lambda enforces the correct number of arguments, and a proc doesn't. And from that documentation, about the only way to convert a proc into a lambda is shown in this example:
define_method always defines a method without the tricks, even if a non-lambda Proc object is given. This is the only exception which the tricks are not preserved.
class C
define_method(:e, &proc {})
end
C.new.e(1,2) => ArgumentError
C.new.method(:e).to_proc.lambda? => true
If you want to avoid polluting any class, you can just define a singleton method on an anonymous object in order to coerce a proc to a lambda:
def convert_to_lambda &block
obj = Object.new
obj.define_singleton_method(:_, &block)
return obj.method(:_).to_proc
end
p = Proc.new {}
puts p.lambda? # false
puts(convert_to_lambda(&p).lambda?) # true
puts(convert_to_lambda(&(lambda {})).lambda?) # true
It is not possible to convert a proc to a lambda without trouble. The answer by Mark Rushakoff doesn't preserve the value of self in the block, because self becomes Object.new. The answer by Pawel Tomulik can't work with Ruby 2.1, because define_singleton_method now returns a Symbol, so to_lambda2 returns :_.to_proc.
My answer is also wrong:
def convert_to_lambda &block
obj = block.binding.eval('self')
Module.new.module_exec do
define_method(:_, &block)
instance_method(:_).bind(obj).to_proc
end
end
It preserves the value of self in the block:
p = 42.instance_exec { proc { self }}
puts p.lambda? # false
puts p.call # 42
q = convert_to_lambda &p
puts q.lambda? # true
puts q.call # 42
But it fails with instance_exec:
puts 66.instance_exec &p # 66
puts 66.instance_exec &q # 42, should be 66
I must use block.binding.eval('self') to find the correct object. I put my method in an anonymous module, so it never pollutes any class. Then I bind my method to the correct object. This works though the object never included the module! The bound method makes a lambda.
66.instance_exec &q fails because q is secretly a method bound to 42, and instance_exec can't rebind the method. One might fix this by extending q to expose the unbound method, and redefining instance_exec to bind the unbound method to a different object. Even so, module_exec and class_exec would still fail.
class Array
$p = proc { def greet; puts "Hi!"; end }
end
$q = convert_to_lambda &$p
Hash.class_exec &$q
{}.greet # undefined method `greet' for {}:Hash (NoMethodError)
The problem is that Hash.class_exec &$q defines Array#greet and not Hash#greet. (Though $q is secretly a method of an anonymous module, it still defines methods in Array, not in the anonymous module.) With the original proc, Hash.class_exec &$p would define Hash#greet. I conclude that convert_to_lambda is wrong because it doesn't work with class_exec.
Here is possible solution:
class Proc
def to_lambda
return self if lambda?
# Save local reference to self so we can use it in module_exec/lambda scopes
source_proc = self
# Convert proc to unbound method
unbound_method = Module.new.module_exec do
instance_method( define_method( :_proc_call, &source_proc ))
end
# Return lambda which binds our unbound method to correct receiver and calls it with given args/block
lambda do |*args, &block|
# If binding doesn't changed (eg. lambda_obj.call) then bind method to original proc binding,
# otherwise bind to current binding (eg. instance_exec(&lambda_obj)).
unbound_method.bind( self == source_proc ? source_proc.receiver : self ).call( *args, &block )
end
end
def receiver
binding.eval( "self" )
end
end
p1 = Proc.new { puts "self = #{self.inspect}" }
l1 = p1.to_lambda
p1.call #=> self = main
l1.call #=> self = main
p1.call( 42 ) #=> self = main
l1.call( 42 ) #=> ArgumentError: wrong number of arguments (1 for 0)
42.instance_exec( &p1 ) #=> self = 42
42.instance_exec( &l1 ) #=> self = 42
p2 = Proc.new { return "foo" }
l2 = p2.to_lambda
p2.call #=> LocalJumpError: unexpected return
l2.call #=> "foo"
Should work on Ruby 2.1+
Cross ruby compatiable library for converting procs to lambdas:
https://github.com/schneems/proc_to_lambda
The Gem:
http://rubygems.org/gems/proc_to_lambda
The above code doesn't play nicely with instance_exec but I think there is simple fix for that. Here I have an example which illustrates the issue and solution:
# /tmp/test.rb
def to_lambda1(&block)
obj = Object.new
obj.define_singleton_method(:_,&block)
obj.method(:_).to_proc
end
def to_lambda2(&block)
Object.new.define_singleton_method(:_,&block).to_proc
end
l1 = to_lambda1 do
print "to_lambda1: #{self.class.name}\n"
end
print "l1.lambda?: #{l1.lambda?}\n"
l2 = to_lambda2 do
print "to_lambda2: #{self.class.name}\n"
end
print "l2.lambda?: #{l2.lambda?}\n"
class A; end
A.new.instance_exec &l1
A.new.instance_exec &l2
to_lambda1 is basically the implementation proposed by Mark, to_lambda2 is a "fixed" code.
The output from above script is:
l1.lambda?: true
l2.lambda?: true
to_lambda1: Object
to_lambda2: A
In fact I'd expect instance_exec to output A, not Object (instance_exec should change binding). I don't know why this work differently, but I suppose that define_singleton_method returns a method that is not yet bound to Object and Object#method returns an already bound method.