Ruby 中同名的局部变量和方法?

Local variables and methods with the same name in Ruby?

def gen_times(factor) do
  return Proc.new {|n| n*factor}
end

gen_times.class # ArgumentError 0 for 1
gen_times(3).class # Proc
gen_times = 2
gen_times.class # Fixnum
times3 = gen_times(3) # A normal, working Proc

第一个 gen_times.class 给出了一个 ArgumentError,所以我假设它 return 是 gen_times 的 return 值的 class 名称,即在下一行确认。

但是,我分配 gen_times,它变成了 Fixnum。但是,我仍然可以使用 gen_times 到 return Procs.

我记得 Fixnum 对象有立即值,对象本身用于赋值,而不是对它的引用。

那么,说 gen_times 是一个引用方法的 Fixnum 对象对吗?

在ruby中你可以有同名的局部变量和方法。这有一些复杂性,例如 类:

中的 setter 方法
class Test
  def active
    @active
  end

  def active=(value)
    @active = value
  end

  def make_active
    active = true
  end
end

t1 = Test.new
t1.active = true
t1.active #=> true

t2 = Test.new
t2.make_active
t2.active #=> nil

t1 对象的代码将 return 预期结果,但 t2 的代码 returns 为零,因为 make_active 方法实际上是创建局部变量而不是调用 active= 方法。您需要编写 self.active = true 才能使这项工作正常进行。

当您写 gen_class 时,ruby 尝试访问局部变量,如果未定义 ruby 尝试调用方法。您可以通过编写 gen_class().

显式调用您的方法