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