Ruby - block scope



我有一个方法,我希望根据场景采取不同的行动,所以我希望能够将块传递给该方法,并在给定块的情况下执行。

然而,我被我所传递的块中变量的范围弄糊涂了

例如:

def original_method (a, b, opt = {id: nil, id_map: {}})
  element_id = (opt[:id_map])
  yield if block_given?
end

还有一种新的方法:

def new_method(a, b, opt)
 original_method (a, b, opt) do
  if(element_id.include? "some text")
    puts "it has some text"
  end
 end
end

但我得到了错误:

undefined local variable or method `element_id' 

在屈服线上。

这能做到吗?

您需要传递局部变量element_id,作为yield的参数。

def original_method (a, b, opt = {id: nil, id_map: {}})
  element_id = opt[:id_map]
  yield(element_id) if block_given? # pass it as argument
end

然后接受它像:

def new_method(a, b, opt)
 original_method (a, b, opt) do | element_id | # receive as block pramater
  if(element_id.include? "some text")
    puts "it has some text"
  end
 end
end

element_id局部变量已经在方法original_method中创建,这就是为什么它只能在该方法中访问。

在方法new_method中,当调用带有的方法original_method时,由于闭包功能,它可以从开始到创建块的点访问方法new_method中的所有变量。

回答您的间接问题:

块的作用域是词法,这意味着它们可以从定义的作用域访问变量(而不是"在中使用")。