开发者

Alias for instance variables?

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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜