Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Ruby Programming
Previous Page Home Next Page

Collecting Hash Arguments

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)
    # ...
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

Ruby Programming
Previous Page Home Next Page

  Published under the terms of the Open Publication License Design by Interspire