TIL: alias in Ruby

drbragg

Drew Bragg

Posted on June 2, 2020

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?

💖 💪 🙅 🚩
drbragg
Drew Bragg

Posted on June 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

TIL: alias in Ruby
todayilearned TIL: alias in Ruby

June 2, 2020