An Interest In:
Web News this Week
- March 27, 2024
- March 26, 2024
- March 25, 2024
- March 24, 2024
- March 23, 2024
- March 22, 2024
- March 21, 2024
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 to 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) endend
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? # => falsemy_todo.mark_complete = truemy_todo.done? # => true
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
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? # => falsemy_todo.mark_complete = truemy_todo.done? # => true
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?
Original Link: https://dev.to/drbragg/til-alias-in-ruby-5c0c
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To