Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling a hash as a function argument

I am using Ruby on Rails 3 and I am trying to handle a hash as a function argument.

For example, if I state a function this way:

def function_name(options = {})
  ...
end

I would like to pass to the function_name a hash like

{"key1"=>"value_1", "key2"=>"value2", "..." => "..."}

and then use that inside the function.

What is the best\common (Rails) way to do that?

P.S.: I have seen the extract_option! method somewhere, but I don't know where I can find some documentation and whether I need that in order to accomplish what I aim.

like image 234
user502052 Avatar asked Mar 15 '11 22:03

user502052


1 Answers

Simply use the definition you provided:

def function_name(options = {})
  puts options["key1"]
end

Call it with:

function_name "key1" => "value1", "key2" => "value2"

or

function_name({"key1" => "value1", "key2" => "value2"})

Array#extract_options! is simply used with methods that have variable method arguments like this:

def function_name(*args)
  puts args.inspect
  options = args.extract_options!
  puts options["key1"]
  puts args.inspect
end

function_name "example", "second argument", "key1" => "value"
# prints
["example", "second argument", { "key1" => "value" }]
value
["example", "second argument"]

Another useful method is Hash#symbolize_keys! which lets you not care about whether you pass in strings or symbols to your function so that you can always access things like this options[:key1].

like image 107
Jakub Hampl Avatar answered Oct 05 '22 08:10

Jakub Hampl