Ruby构造函数vs vs @

我创建了以下简单的类:

class Test
  def initialize(a, b)
    @a = a
    @b = b
  end

  def test
    puts @a
  end
end

有没有办法用self替换@a ? 每次我试图做到这一点,我收到一个错误:

undefined method `a'

我这样做的原因是因为我想创建一个带有两个参数的新对象,然后对这些参数进行操作,如:

d = MyObject('title', 'Author')
d.showAuthor

它可以完成,实际上是为这些类完成的:Array,String,Integer,Float,Rational,Complex和Hash。 如果考虑到同等重要的Test类(不好的名字),那么考虑:

class Test
  def initialize(a, b)
    @a = a
    @b = b
  end

  def test
    puts @a
  end
end

module Kernel
  def Test(*args)
    Test.new(*args)  #that's right, just call new anyway!
  end
end

book = Test('title', 'Author')
book.test # => title

由于Kernel模块被Object继承,所以全局命名空间现在有一个Test方法。 除非你绝对需要,否则不要这样做。


class Test
  attr_accessor :a,:b   #creates methods a,b,a=,b= and @a and @b variables

  def initialize(a, b)
    self.a = a  #calls a=
    self.b = b  #calls b=
  end

  def test
    puts a  #calls method a; self.a would do the same.
  end

  def self.[](a,b)
    new(a,b)
  end
end

这会让你放弃新的(但你必须改变方括号)所以你可以打电话给:

d=Test['dog','cat']
d.a  #'dog'

所以你需要从实例外部访问你的实例变量? 你可以使用attr_accessor来做到这一点:

class Test
  attr_accessor :a
  attr_accessor :b

  def initialize(a, b)
    @a = a
    @b = b
  end
end

t = Test.new(:foo, :bar)
t.a
t.b

attr_accessor让我们读取和写入实例变量。 如果你只需要读取它,你可以使用attr_reader ,如果你只需要改变它,你可以使用attr_writer

有关属性访问器的更多信息,请访问:https://stackoverflow.com/a/4371458/289219

链接地址: http://www.djcxy.com/p/25787.html

上一篇: Ruby constructor self vs @

下一篇: How does ActiveRecord define methods compared to attr