An alias, such as variables?

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

For ex:

@imavar

alias_attribute(@hesavar, @imavar)
+3
source share
2 answers

You can use get get methods instead.

+6
source

There are no attributes in Ruby. When you use attr_reader :imavar, you create a method to retrieve the value:

def imavar
  @imavar
end

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

alias_method :hesavar, :imavar

Full example:

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
+6
source

Source: https://habr.com/ru/post/1751929/


All Articles