Quick Tip: Setting Variables Inside Array & Hash Literals

Did you know that you can assign variables inside Ruby’s array and hash literals?

While the values used inside square bracket array literals are typically hard-coded, provided by a variable, computed from an inline expression or generated by a method, any valid Ruby statement can be used. The same is true for both keys and values used in hash literal key => value pairs.

Since a Ruby assignment statement returns the value assigned (e.g. middle = 2 returns 2), these examples have equivalent effect:

middle = 2
list = [1, middle, 3]
# list = [1, 2, 3]; middle = 2
list = [1, middle = 2, 3]
# list = [1, 2, 3]; middle = 2

Variables set within a literal can be accessed later from within the same literal as well as from outside it:

list = [1, special = 2, special + 1, 4]
# list = [1, 2, 3, 4]; special = 2

hash = { key = :one => key.to_s + "'s value", :two => special }
# hash = { :one => "one's value", :two => 2 }; key = :one

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>