开发者

Alias for instance variables?

开发者 https://www.devze.com 2023-01-05 01:14 出处:网络
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?

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

精彩评论

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