方法的 ruby​​ 关键字参数 [英] ruby keyword arguments of method

查看:46
本文介绍了方法的 ruby​​ 关键字参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何像 rails 一样声明一个带有关键字参数的方法.一些例子可能是

How can I declare a method with keyword arguments just like rails do. some examples may be

Person.find(:all, :conditions => "..."). 

如何使用符号创建与上述类似的方法?

How can I use symbols to create methods similar to the above?

我对 ruby​​ 很陌生.提前致谢!

I am very new to ruby. Thanks in advance!

推荐答案

Ruby 实际上没有关键字参数.Rails 正在利用 Ruby 的一个特性,它允许您省略散列周围的大括号.例如,对于find,我们真正调用的是:

Ruby doesn't actually have keyword arguments. Rails is exploiting a feature of Ruby which lets you omit the braces around a hash. For example, with find, what we're really calling is:

Person.find(:all, { :conditions => "...", :offset => 10, :limit => 10 } )

但是如果散列是方法的最后一个参数,您可以省略大括号,它仍然会被视为散列:

But if the hash is the last argument of the method, you can leave out the braces and it will still be treated as a hash:

Person.find(:all, :conditions => "...", :offset => 10, :limit => 10)

您可以在自己的方法中使用它:

You can use this in your own methods:

def explode(options={})
    defaults = { :message => "Kabloooie!", :timer => 10, :count => 1 }
    options = defaults.merge(options)

    options[:count].times do
        sleep options[:timer]
        puts options[:message]
    end
end

然后调用它:

explode :message => "Meh.", :count => 3

或者不带参数调用它,导致使用所有默认值:

Or call it without an argument, resulting in all default values being used:

explode

这篇关于方法的 ruby​​ 关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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