【问题标题】:Local variables and methods with the same name in Ruby?Ruby中同名的局部变量和方法?
【发布时间】:2015-04-25 11:24:55
【问题描述】:
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 对象对吗?

【问题讨论】:

  • 局部变量和局部函数可以使用相同的名称。为了明确区分它们,可以使用括号。
  • 我不得不读了几遍才能弄清楚你在问什么。我认为如果您显示与代码本身内联运行代码的结果会更好,无论是作为 cmets,还是以“我试过这个:......然后发生这种情况:......所以我尝试了这个: ...然后发生了:...”

标签: ruby object methods


【解决方案1】:

在 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() 来显式调用您的方法。

【讨论】:

    猜你喜欢
    • 2011-06-16
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多