Is there a way to create aliases for instance variables (not talking about db alias attributes) other th开发者_开发技巧an assigning it to another instance var?
For ex:
@imavar
alias_attribute(@hesavar, @imavar)
You can alias getter methods instead.
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 an 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
精彩评论