相关疑难解决方法(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中创建惯用对象

在ruby中,我经常发现自己编写以下内容:

class Foo
  def initialize(bar, baz)
    @bar = bar
    @baz = baz
  end

  << more stuff >>

end
Run Code Online (Sandbox Code Playgroud)

甚至

class Foo
  attr_accessor :bar, :baz

  def initialize(bar, baz)
    @bar = bar
    @baz = baz
  end

  << more stuff >>

end
Run Code Online (Sandbox Code Playgroud)

我总是希望尽可能地减少样板 - 所以有没有更惯用的方式在ruby中创建对象?

ruby

14
推荐指数
2
解决办法
1963
查看次数

标签 统计

ruby ×2

instance-variables ×1

self ×1