程序的约束

Jim*_*oho 31 ruby binding

是否可以在另一个对象的上下文中执行proc?

我知道通常你会做proc.call(foo),然后块应该定义一个参数.我想知道我是否可以"自我"绑定到foo,因此没有必要有一个块参数.

proc = Proc.new { self.hello }

class Foo
  def hello
    puts "Hello!"
  end
end

foo = Foo.new

# How can proc be executed within the context of foo
# such that it outputs the string "Hello"?

proc.call
Run Code Online (Sandbox Code Playgroud)

Chu*_*uck 45

foo.instance_eval &proc
Run Code Online (Sandbox Code Playgroud)

instance_eval可以取块而不是字符串,&操作符将proc转换为块以与方法调用一起使用.

  • 如果你运行```foo.instance_exec(params,&proc)```你也可以在上下文中将参数传递给函数. (13认同)