Željko Filipin's blog.
Home Blog Tags Now License

View on GitHub
9 February 2007

Ruby Hashes (2)

by Željko Filipin

Yesterday I wrote about Ruby hashes. Use it and you can write nice looking code.

edit({"security" => "low"})

def edit(properties)
  edit_title(properties["title"]) if properties["title"]
  # ...
  edit_security(properties["security"]) if properties["security"]

Instead of ugly code.

edit(nil, nil, nil, nil, nil, nil, security)

def edit(title = nil, url = nil, mail = nil, description = nil, membership = nil, status = nil, security = nil)
  edit_title(title) if title
  # ...
  edit_security(security) if security

I got interested when I saw this at wtr-general

ie.div(:name => 'foo', :index => 2).click

This will find the second div with the name foo.

I tried to do something like that, but this was the best I could think of.

div(:name => 'foo', :index => 2)

def div(first, second)
  hash = {first, second}
  puts hash[:name]
  puts hash[:index]

And, of course, it did not work.

ArgumentError: wrong number of arguments (1 for 2)

I posted my problem to wtr-general and Charley Baker was kind enough to help me. A link to Collecting Hash Arguments from Programming Ruby said it all.

div(:name => 'foo', :index => 2)

def div(properties)
  puts properties[:name]
  puts properties[:index]
tags: code - ruby