yield self和instance_eval用法区别

时间:2023-03-08 21:19:49
yield self和instance_eval用法区别
class Foo
def initialize(&block)
instance_eval(&block) if block_given?
end
end
class Foo
def initialize
yield self if block_given?
end
end
x = Foo.new {|obj| def obj.foo() 'foo' end}
x.foo

By using instance_eval you're evaluating the block in the context of your object. This means that using def will define methods on that object. It also means that calling a method without a receiver inside the block will call it on your object.

使用 instance_eval 对象是执行代码快的上下文,意味着使用del 定义方法在对象上,意味着没有使用接收者调用方法,对象就是接收者

When yielding self you're passing self as an argument to the block, if your block doesn't take any arguments, it is simply ignored.

当使用yield self时,传递self作为参数给代码快,如果代码快没有接收任何参数,那么self就被忽略,

例子

class Thing
attr_accessor :name def initialize
yield self if block_given?
end end def given(foo:)
yield(Thing.new do |thing|
thing.name=foo
end)
end given(foo: 'jack') do |thing|
p thing.name
end