相关疑难解决方法(0)

实例变量:self vs @

这是一些代码:

class Person
  def initialize(age)
    @age = age
  end

  def age
    @age
  end

  def age_difference_with(other_person)
    (self.age - other_person.age).abs
  end

  protected :age
end
Run Code Online (Sandbox Code Playgroud)

我想知道的是两者的区别@age,并self.ageage_difference_with方法.

ruby instance-variables self

175
推荐指数
4
解决办法
4万
查看次数

为什么Ruby setter需要"自我".课程内的资格?

Ruby setters - 无论是由类创建(c)attr_accessor还是手动创建- 似乎是self.在类本身内访问时需要限定的唯一方法.这似乎使Ruby独自成为语言世界:

  • 所有方法都需要self/ this(像Perl,我认为是Javascript)
  • 没有方法需要self/ this是(C#,Java)
  • 只有setter需要self/ this(Ruby?)

最好的比较是C#VS红宝石,因为这两种语言都支持这句法工作就像类的实例变量的访问方法:foo.x = y,y = foo.x.C#称它们为属性.

这是一个简单的例子; Ruby中的相同程序然后是C#:

class A
  def qwerty; @q; end                   # manual getter
  def qwerty=(value); @q = value; end   # manual setter, but attr_accessor is same 
  def asdf; self.qwerty = 4; end        # "self." is necessary in ruby?
  def xxx; asdf; end                    # we can invoke nonsetters w/o "self." …
Run Code Online (Sandbox Code Playgroud)

ruby

70
推荐指数
3
解决办法
9384
查看次数

标签 统计

ruby ×2

instance-variables ×1

self ×1