To be clear - this code is running perfectly - code with proc
要清楚 - 这段代码运行完美 - 带proc的代码
but if instead I change Proc.new to lambda, I'm getting an error
但如果相反我将Proc.new更改为lambda,我收到错误
ArgumentError: wrong number of arguments (1 for 0)
May be this is because instance_eval wants to pass self as a param, and lambda treats as a method and do not accept unknown params?
可能这是因为instance_eval想要将self作为一个参数传递,而lambda视为一种方法并且不接受未知的params?
There is two examples - first is working:
有两个例子 - 首先是工作:
class Rule
def get_rule
Proc.new { puts name }
end
end
class Person
attr_accessor :name
def init_rule
@name = "ruby"
instance_eval(&Rule.new.get_rule)
end
end
second is not:
第二个不是:
class Rule
def get_rule
lambda { puts name }
end
end
class Person
attr_accessor :name
def init_rule
@name = "ruby"
instance_eval(&Rule.new.get_rule)
end
end
Thanks
1 个解决方案
#1
4
You are actually correct in your assumption. Self is being passed to the Proc
and to the lambda as it is being instance_eval
'ed. A major difference between Procs and lambdas is that lambdas check the arity of the block being being passed to them.
你的假设实际上是正确的。 Self正被传递给Proc和lambda,因为它是instance_eval。 Procs和lambdas之间的一个主要区别是lambdas检查正在传递给它们的块的arity。
So:
class Rule
def get_rule
lambda { |s| puts s.inspect; puts name; }
end
end
p = Person.new
p.get_rule
#<Person:0x007fd1099f53d0 @name="ruby">
ruby
Here I told the lambda to expect a block with arity 1 and as you see in the argument inspection, the argument is indeed the self
instance of Person class.
在这里,我告诉lambda期望一个带有arity 1的块,正如你在参数检查中看到的那样,该参数确实是Person类的自我实例。
#1
4
You are actually correct in your assumption. Self is being passed to the Proc
and to the lambda as it is being instance_eval
'ed. A major difference between Procs and lambdas is that lambdas check the arity of the block being being passed to them.
你的假设实际上是正确的。 Self正被传递给Proc和lambda,因为它是instance_eval。 Procs和lambdas之间的一个主要区别是lambdas检查正在传递给它们的块的arity。
So:
class Rule
def get_rule
lambda { |s| puts s.inspect; puts name; }
end
end
p = Person.new
p.get_rule
#<Person:0x007fd1099f53d0 @name="ruby">
ruby
Here I told the lambda to expect a block with arity 1 and as you see in the argument inspection, the argument is indeed the self
instance of Person class.
在这里,我告诉lambda期望一个带有arity 1的块,正如你在参数检查中看到的那样,该参数确实是Person类的自我实例。