[reference: Programming Ruby 2nd]
Some languages feature keyword arguments—that is, instead of passing arguments in a given order and quantity, you pass the name of the argumentwith its value,in any order.
Ruby 1.8 does not have keyword arguments. In the meantime, people are
using hashes as a way of achieving the same effect.
class SongList
def create_search(name, params)
# ...
end
end
list.create_search("short jazz songs",
{
'genre' => "jazz",
'duration_less_than' => 270
})
The first parameter is the search name, and the second is a hash literal containing search parameters. The use of a hash means we can simulate keywords: look for songs with a genre of “jazz” and a duration less than 4 12 minutes. However, this approach is slightly clunky, and that set of braces could easily be mistaken for a block associated with the method. So,
Ruby has a shortcut. You can place key => value pairs in an argument list
, as long as they follow any normal arguments and precede any array and block arguments.
All these pairs will be collected into a single hash and passed as one argument to the method. No braces are needed.
list.create_search('short jazz songs',
'genre' => 'jazz',
'duration_less_than' => 270)
Finally, in idiomatic Ruby you’d probably use symbols rather than strings, as symbols
make it clearer that you’re referring to the name of something.
list.create_search('short jazz songs',
:genre => :jazz,
:duration_less_than => 270)
A well-written Ruby program will typically contain many methods, each quite small,
so it’s worth getting familiar with the options available when defining and using Ruby
methods.