如何方法使用哈希参数在Ruby中? [英] How do methods use hash arguments in Ruby?

查看:217
本文介绍了如何方法使用哈希参数在Ruby中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一些库方法作为我一直在学习哈希参数。

I saw hash arguments used in some library methods as I've been learning.

例如,

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?

推荐答案

例如:

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:

foo("regular argument", a: 12, :b => 13)

它实际上是一个语法糖为:

It's actually a syntactic sugar for:

foo("regular argument", {a: 12, :b => 13})

此外, {A:12} 语法糖{:A => 12}

当所有这一切都是结合在一起,你会得到一个语法类似于其他语言命名的参数。

When all of this is combined together, you get a syntax that looks similar to named arguments in other languages.

这篇关于如何方法使用哈希参数在Ruby中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆