开发者

class inheritance in ruby / rails

so this is what i want to do:

class A
  ATTRS = []

  def list_attrs
    puts ATTRS.inspect
  end
end

class B < A
  ATTRS = [1,2]
end

a = A.new
b = B.new
a.list_attrs
b.list_attrs

i want to create a base class with a method that plays with the ATTRS attribute of the class. in 开发者_如何学JAVAeach inherited class there will be a different ATTRS array

so when i call a.list_attrs it should print an empty array and if i call b.attrs should put [1,2].

how can this be done in ruby / ruby on rails?


It is typically done with methods:

class A
  def attrs
    []
  end

  def list_attrs
    puts attrs.inspect
  end
end

class B < A
  def attrs
    [1,2]
  end
end


modf's answer works... here's another way with variables. (ATTRS is a constant in your example)

class A
  def initialize
    @attributes = []
  end

  def list_attrs
    puts @attributes.inspect
  end
end

class B < A
  def initialize
    @attributes = [1,2]
  end
end


I don't think it's a good idea to create the same array each time a method is called. It's more natural to use class instance variables.

class A
  def list_attrs; p self.class.attrs end
end
class << A
  attr_accessor :attrs
end

class A
  @attrs = []
end
class B < A
  @attrs = [1, 2]
end
A.new.list_attrs # => []
B.new.list_attrs # => [1, 2]

You can also use constants along the line suggested in the question:

class A
  def list_attrs; p self.class.const_get :ATTRS end
  ATTRS = []
end
class B < A
  ATTRS = [1, 2]
end
A.new.list_attrs # => []
B.new.list_attrs # => [1, 2]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜