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

查看:25
本文介绍了方法如何在 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)

我使用 hash={} 来指定最后一个参数是一个散列,默认值为空散列.现在,当我写:

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天全站免登陆