为什么Ruby setter需要“自我”。课程内的资格?

时间:2008-09-04 20:36:17

标签: ruby

3 个答案:

答案 0 :(得分:82)

嗯,我认为这种情况的原因是因为qwerty = 4不明确 - 您是在定义一个名为qwerty的新变量还是调用setter? Ruby通过说它将创建一个新变量来解决这种歧义,因此self.是必需的。

以下是您需要self.的另一种情况:

class A
  def test
    4
  end
  def use_variable
    test = 5
    test
  end
  def use_method
    test = 5
    self.test
  end
end
a = A.new
a.use_variable # returns 5
a.use_method   # returns 4

如您所见,test的访问权限不明确,因此需要self.

此外,这就是为什么C#示例实际上不是一个很好的比较,因为你以一种明确的方式定义变量,使用setter。如果您在C#中定义了与访问者同名的变量,则需要使用this.限定对访问者的调用,就像Ruby案例一样。

答案 1 :(得分:18)

这里要记住的重要事情是Ruby方法可以在任何时候定义(un),因此为了智能地解决歧义,每个赋值都需要运行代码来检查是否存在具有赋值名称的方法在转让时。

答案 2 :(得分:16)

因为否则无法在方法内部设置局部变量。 variable = some_value含糊不清。例如:

class ExampleClass
  attr_reader :last_set
  def method_missing(name, *args)
    if name.to_s =~ /=$/
      @last_set = args.first
    else
      super
    end
  end

  def some_method
    some_variable = 5 # Set a local variable? Or call method_missing?
    puts some_variable
  end
end

如果设置者不需要self,则some_method会引发NameError: undefined local variable or method 'some_variable'。但是,该方法按预期工作:

example = ExampleClass.new
example.blah = 'Some text'
example.last_set #=> "Some text"
example.some_method # prints "5"
example.last_set #=> "Some text"