Filipin.eu

Željko Filipin's blog.
Home Blog Tags 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)
  prepare_for_edit
  edit_title(properties["title"]) if properties["title"]
  # ...
  edit_security(properties["security"]) if properties["security"]
  check_after_edit
end

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)
  prepare_for_edit
  edit_title(title) if title
  # ...
  edit_security(security) if security
  check_after_edit
  end

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]
end

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]
end
tags: code - ruby