方法如何在 Ruby 中使用哈希参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16576477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do methods use hash arguments in Ruby?
提问by Senjai
I saw hash arguments used in some library methods as I've been learning.
在我学习的过程中,我看到了一些库方法中使用的哈希参数。
E.g.,
例如,
list.search(:titles, genre: 'jazz', duration_less_than: 270)
Can someone explain how a method uses arguments like this, and how you could create a method that makes use of Hash arguments?
有人可以解释一个方法如何使用这样的参数,以及如何创建一个使用 Hash 参数的方法?
回答by Idan Arye
Example:
例子:
def foo(regular, hash={})
puts "regular: #{regular}"
puts "hash: #{hash}"
puts "a: #{hash[:a]}"
puts "b: #{hash[:b]}"
end
foo("regular argument", a: 12, :b => 13)
I use hash={}to specify that the last argument is a hash, with default value of empty hash. Now, when I write:
我hash={}用来指定最后一个参数是一个散列,默认值为空散列。现在,当我写:
foo("regular argument", a: 12, :b => 13)
It's actually a syntactic sugar for:
它实际上是一个语法糖:
foo("regular argument", {a: 12, :b => 13})
Also, {a: 12}is syntactic sugar for {:a => 12}.
此外,{a: 12}是{:a => 12}.
When all of this is combined together, you get a syntax that looks similar to named arguments in other languages.
当所有这些组合在一起时,您会得到一种语法,看起来类似于其他语言中的命名参数。
回答by Boris Stitnicky
In Ruby 2.x, you can use **hash splat:
在 Ruby 2.x 中,你可以使用**hash splat:
def foo( ordered_argument, **named_arguments )
puts "Ordered argument: #{ordered_argument}"
puts "Named arguments: #{named_arguments}"
end
foo( :titles, genre: 'jazz', duration_less_than: 270 )
#=> Ordered argument: titles
#=> Named arguments: {:genre=>"jazz", :duration_less_than=>270}
回答by Brent Royal-Gordon
When a Ruby method call's argument list ends in one or more key-value pairs, like foo: 'bar'or 'foo' => 1, Ruby collects them all into a single hash and passes that hash as the last parameter. You can see that yourself in irb:
当 Ruby 方法调用的参数列表以一个或多个键值对(如foo: 'bar'或 )结尾时'foo' => 1,Ruby 会将它们全部收集到一个散列中,并将该散列作为最后一个参数传递。你可以看到自己在irb:
irb(main):002:0> puts foo: 'bar', baz: 'quux'
{:foo=>"bar", :baz=>"quux"}
=> nil
Thus, you can add a final, optional parameter to a method you're writing to receive this hash. You'll usually want to default it to an empty hash. You can call the parameter anything you want, but optionsis a common name:
因此,您可以将最终的可选参数添加到您正在编写的方法中以接收此散列。您通常希望将其默认为空哈希。您可以随意调用参数,但它options是一个通用名称:
def my_method(a, b, c, options = {})
...
end
One useful trick if you're using Rails: It's often handy to treat plain strings and symbols as equivalent. Rails adds a symbolize_keys!method to Hashto convert all string keys to symbols:
如果您使用 Rails,一个有用的技巧是:将普通字符串和符号视为等效通常很方便。Rails添加一个symbolize_keys!方法来Hash给所有字符串键转换为符号:
def my_method(a, b, c, options = {})
options.symbolize_keys!
...
end
回答by M.Octavio
I would do one of two options:
我会做以下两种选择之一:
1- if a got a large number of arguments to pass into a method I would use a hash like this:
1-如果有大量参数传递给方法,我将使用这样的散列:
some_method({titles => 'titulo', genre => 'jazz', duration_less_than => 270})
or
或者
my_hash = {titles => 'titulo', genre => 'jazz', duration_less_than => 270}
some_method(my_hash)
and
和
def some_method(hash_options)
#important code
end
2- option will be more 'traditional'
2-选项将更“传统”
some_method('titulo', 'jazz', 270)
def some_method(titles, genre, duration_less_than)
#important code
end
回答by Dennis
Since Ruby 2.0 you can use keyword arguments [1][2]as opposed to the single Hash parameter.
从 Ruby 2.0 开始,您可以使用关键字参数[1][2]而不是单个 Hash 参数。
def foo(keyword_arg: 'bar')
keyword_arg
end
And here's how it behaves.
这是它的行为方式。
> foo
=> "bar"
> foo(keyword_arg: 'baz')
=> "baz"
回答by tokhi
This is how I do it:
这就是我的做法:
def my_method(title, args)
puts title
puts args
passing parameters:
传递参数:
my_method('test title', a: 'foo', b: 'bar')
# => test title
# => '{:a => 'foo', :b => 'bar'}

