Some languages feature ``keyword arguments''---that is, instead of
passing arguments in a given order and quantity, you pass the name
of the argument with its value, in any order. Ruby 1.6 does not have
keyword arguments (although they are scheduled to be implemented in
Ruby 1.8).
In the meantime, people are using hashes as a way of achieving the
same effect. For example, we might consider adding a more powerful
named-search facility to our
SongList
.
class SongList
def createSearch(name, params)
# ...
end
end
aList.createSearch("short jazz songs", {
'genre' => "jazz",
'durationLessThan' => 270
} )
|
The first parameter is the search name, and the second is a hash literal
containing search parameters. The use of a hash means that we can
simulate keywords: look for songs with a genre of ``jazz'' and a
duration less than 4 1/2 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 short cut. 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.
aList.createSearch("short jazz songs",
'genre' => "jazz",
'durationLessThan' => 270
)
|