RubyA trick with Ruby array literals
Originally published here
Declaring an array in Ruby is simple:
However, did you know you can save the array elements as variables the exact same time you declare them?
Looking like some magic? Well, it is not magic 🙂. This happens because assigning a value to a variable is an expression in Ruby. This is applicable to many other cases, like assigning a value on a conditional :
Or even crazier: to save the parameter you pass to a method!
Disclaimer: ☝️ those 2 might be bad ideas. I wouldn't use it regularly on any code I write but knowing it is possible is always a good thing.
What can I apply this?
It plays quite well with constants that can then be used as some kind of enums:
On rails apps they are especially useful to declare scopes:
Pretty cool, right? This is the first post in a four part series of Ruby tricks. Feel free to check the rest out.