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.
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]
.
The way you have it declared in your example will work fine.
def function(options = {})
item = options[:item]
need_milk = options[:milk] || false
cow = options[:bovine]
end
function(:item => "Something")
In the case above, item == "Something"
, need_milk == false
and cow == nil
.
extract_options
is simply an addition to the Array and Hash
class via Rails.
def function(something, else, *args)
options = args.extract_options! # returns Hash
end
It is useful if you plan on having many different types of parameters in args
but if you only want Hash
options, your original way is fine.
Here's a Gist of the code in Rails for extract_options!
I personally use it in my code at work by just writing it to an external file and requiring it into my project.
Ruby makes this easy, and you were already doing it right.
Here is a poetry-mode (minimal, DSL-style) example:
def f x = {}
p x
end
f :a => :b
{:a=>:b}
f
{}
f :a => :b, :c => :d
{:a=>:b, :c=>:d}
精彩评论