Neat Ruby Tricks: Named Parameters with Ruby 1.9
One of the syntax sugar additions to Ruby 1.9 is the new syntax for specifying hashes with symbols as keys. In 1.9 you can now specify the hash on line 1 in the format on line 2.
1 { :manufacturer => 'Lenovo', :model => 'Thinkpad R500' } 2 { manufacturer: 'Lenovo', model: 'Thinkpad R500' }
Now this might not look like much of an improvement but it shines in method calls where we can use ‘naked’ hashes as named parameters. For example in the following code snippet line 1 (Ruby 1.8) is the equivalent to line 2 (Ruby 1.9)
1 get_price( :manufacturer => 'Lenovo', :model => 'Thinkpad R500' ) 2 get_price( manufacturer: 'Lenovo', model: 'Thinkpad R500' )
The expression on line 2 using the new syntax is quite a bit neater (in my own opinion) and makes named parameters even easier to read and parse.
There is one caveat to remember with this and that all keys will be converted into symbols.
1 pc_data = { manufacturer: 'Lenovo', model: 'Thinkpad R500' } 2 pc_data[ :manufacturer ] # => 'Lenovo' 3 pc_data[ 'manufacturer' ] # => nil
Farrel Lifson is a lead developer at Aimred.