rubyalias-method

When should I use an Alias Method? - Ruby


I've looked through and haven't seen an answer to:

What would you use an alias method?

class Vampire
 attr_reader :name, :thirsty

 alias_method :thirsty?, :thirsty
end

Is the only reason I would use one is to be able to use a question mark with whatever method I define? I believe you can't use question marks with instance variables.


Solution

  • I think this is from an earlier question I responded to, where I proposed using alias_method, so I have a little bit of extra context into this to explain it's use in that context.

    In your code snippet, you have a bit of code that reads attr_reader :thirsty that is basically a getter for an instance variable of the same name (@thirsty)

    def thirsty
      @thirsty
    end
    

    In the original code snippet, you had an assertion that was:

    refute vampire.thirsty?
    

    You also had code that simply returned true for thirsty? method, which failed your assertion.

    There are at least two ways you could have modified your code so that the call to thirsty? worked and your assertion passed:

    Create a method that calls the thirsty reader, or access the @thirsty instance variable itself:

    def thirsty?
      thirsty # or @thirsty
    end
    

    The other way is to use alias_method, which is functionally equivalent to the above. It aliases thirsty? to thirsty which is an attr_reader which reads from the @thirsty instance variable

    Reference to the other answer I gave

    You might be better off not using an attr_reader at all, instead just doing as Sergio noted in his comment:

    class Vampire
      def initialize(name)
        @name = name
        @thirsty = true
      end
    
      def thirsty?
        @thirsty
      end
    
      def drink
        @thirsty = false
      end
    end