Ruby constructor self vs @

I have created folowing simple class:

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

  def test
    puts @a
  end
end

IS there a way to replace @a with self ? Everytime I tried to do this I received an error:

undefined method `a'

The reason I am doing this is because I would like to create a new object with two parameters, and later operate on these parameters like:

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

It can be done and actually is done for these classes: Array, String, Integer, Float, Rational, Complex and Hash. If you consider the Test class (bad name by the way) of equal importance then consider:

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

Since the Kernel module is inherited by Object , the global namespace now has a Test method. Don't do this unless you absolutely need it.


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'

So you need to access your instance variables from outside the instance? You can use attr_accessor to do that:

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 let's you both read and write the instance variable. If you only need to read it, you can use attr_reader , and if you only need to change it you can use attr_writer .

More on attribute accessors: https://stackoverflow.com/a/4371458/289219

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

上一篇: Ruby类中“属性”的性质是什么?

下一篇: Ruby构造函数vs vs @