RubyA trick with Ruby array literals

Fran C.

Fran C.

2 minutes read

Originally published here

Declaring an array in Ruby is simple:

1 2 ary = ["foo", "bar"] # => ["foo", "bar"]

However, did you know you can save the array elements as variables the exact same time you declare them?

1 2 3 4 5 6 7 ary = [ foo = "foo", bar = "bar" ] foo # => "foo" bar # => "bar"

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 :

1 2 3 if user = User.find(params[:id]) puts "User is #{}" end

Or even crazier: to save the parameter you pass to a method!

1 2 3 4 5 6 7 8 9 def some_method(arg) puts arg end some_method(value = "Hola") # prints -> "Hola" value # => "Hola"

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:

1 2 scope :non_red, -> { where(color: COLORS - [COLOR_RED]) } scope :blue, -> { where(color: COLOR_BLUE) }

Pretty cool, right? This is the first post in a four part series of Ruby tricks. Feel free to check the rest out.

Fran C.
Staff Software Engineer

I break code for a living... wait no, I fix it, most of the time. Well, sometimes. Yeah, I break code for a living.

Liked this read?Join our team of lovely humans

We're looking for outstanding people like you to become part of our team. Do you like shipping code that adds value on a daily basis while working closely with an amazing bunch of people?

Made with ❤️ by Factorial's Team