2

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?

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

I would say that accessing instance variables in child classes is bad practice (poor encapsulation). You could use attribute readers/writers though, but you'd still have to call super in your initialize methods (except in the trivial case in this example), and in the correct order, too!
@modf: tend to agree with you; I think inheritance itself is overused and should be avoided in most cases
1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.