views:

51

answers:

2

Is there a way to create aliases for instance variables (not talking about db alias attributes) other than assigning it to another instance var?

For ex:

@imavar

alias_attribute(@hesavar, @imavar)
+3  A: 

You can alias getter methods instead.

Eimantas
A: 

Ruby doesn't really have attributes. When you use attr_reader :imavar you are creating a method for retrieving the value:

def imavar
  @imavar
end

So to create a alias for the variable you could create an alias for the method:

alias_method :hesavar, :imavar

The complete example would be:

class DataHolder
  attr_reader :imavar
  alias_method :hesavar, :imavar

  def initialize(value)
    @imavar = value
  end
end

d = DataHolder.new(42)
d.imavar
 => 42
d.hesavar
 => 42
Bryan Ash