DEV Community

Drew Bragg
Drew Bragg

Posted on

TIL: alias in Ruby

Today I learned (learnt?) about the alias keyword in Ruby. I'm not sure how I've gone this long working with ruby without hearing about it but better late than never.

If this is also your first time hearing about alias, let me give you a short intro.

Ruby is a very expressive language. It lets you write code that looks like plain english. Keeping with that trend it's not uncommon for me to do something like this in a class:

class Todo
  attr_accessor :name, :complete

  def initialize(name)
    @name = name
    @complete = false
  end

  def done?
    complete
  end

  def mark_complete=(arg)
    complete=(arg)
  end
end
Enter fullscreen mode Exit fullscreen mode

Ok, I wouldn't actually do that but I'm just illustrating a point.

This works just fine and lets us keep writing our plain english-like syntax

my_todo = Todo.new('Learn about the alias keyword')

my_todo.done? # => false

my_todo.mark_complete = true

my_todo.done? # => true
Enter fullscreen mode Exit fullscreen mode

But, just like most things in Ruby, there is a shorter and better(?) way to do this.

Enter the alias keyword:

class Todo
  attr_accessor :name, :complete

  def initialize(name)
    @name = name
    @complete = false
  end

  alias done? complete
  alias mark_complete= complete=
end
Enter fullscreen mode Exit fullscreen mode

So much shorter and cleaner. I also think it's just as expressive as (if not more than) the original example. And it still works as expected:

my_todo = Todo.new('Learn about the alias keyword')

my_todo.done? # => false

my_todo.mark_complete = true

my_todo.done? # => true
Enter fullscreen mode Exit fullscreen mode

I found the alias keyword to be pretty great and definitely something I'm going to start using in the future.

How about you? What do you think about the alias keyword in Ruby?

Top comments (3)

Collapse
 
user_name profile image
User_name

love it. little gold nuggets like this in ruby make the language so fun to work with. thanks for sharing.

Collapse
 
drbragg profile image
Drew Bragg

Agreed. The more I work with and learn about Ruby the more I love it.

Collapse
 
swiknaba profile image
Lud

Check out alias_method, a similar yet slightly different method for the "same thing". Just to add some confusion here 😁