Ruby中具有相同名称的局部变量和方法?

时间:2015-04-25 11:24:55

标签: ruby object methods

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,所以我假设它返回gen_times的返回值的类名,这在下一行中得到确认。

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

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

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

1 个答案:

答案 0 :(得分:2)

在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对象的代码将返回预期结果,但t2的代码返回nil,因为make_active方法实际上是创建局部变量而不是调用active =方法。您需要编写self.active = true才能使其正常工作。

当你编写gen_class时,ruby尝试访问本地变量,如果没有定义,ruby会尝试调用方法。您可以通过编写gen_class()来显式调用您的方法。