-
Ruby Idioms & Shortcuts: The Splat Operator
The “splat” operator (*) is extremely useful and allows you to take all sorts of crazy shortcuts, the kind of shortcuts that split your wig the first time you see them, but more importantly allow you to write über-concise, expressive code.
Say you have a nested array that you want as a hash, prepend a splat to your array and it will return a hash:
irb(main):001:0> hash = { :name=>"Steve Graham", :age=>24 }
=> { :name=>"Steve Graham", :age=>24 }
irb(main):002:0> array = *hash
=> [[:name, "Steve Graham"], [:age, 24]]Of debatable utility but while we’re here I might as well mention that you can do the reverse using
Hash[]irb(main):003:0> wow = Hash[array]
=> { :name=>"Steve Graham", :age=>24 }Wow! The thought of the amount of nonsense of code that you WON’T have to write now thanks to these little conveniences makes a little tear of joy bead up and teeter precipitously on my eyelid.
Ruby, I ♥ you. Emotional, truly emotional.
What else can we do with the splat? You can use the splat with a case statement:
males = %w(pharrell chad shae) females = %w(cameron jessica alyssa) justin_timberlake = case gender when *females "ladies good morning" when *males "gentlemen goodnite" when *males|females "hahahahaha and that's it" end
You can also use it on any class that includes Enumerable. What it does is call to_a on the object, which collects the entries of the object, in the case of a file, the lines:
irb(main):007:0> lines = *File.open('/etc/hosts'); pp lines
=>
["##\n",
"# Host Database\n",
"#\n",
"# localhost is used to configure the loopback interface\n",
…]Extra Credit:
Although not the splat operator itself, you can join an array using the splat, but in this case it’s an instance method of the Array class (Array#*).
irb(main):008:0> %w(a list of arbitrary words) * ", "
=> "a, list, of, arbitrary, words"
Mon11Jan