简体   繁体   中英

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 each 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM