简体   繁体   English

方法的ruby关键字参数

[英]ruby keyword arguments of method

How can I declare a method with keyword arguments just like rails do. 我怎样才能像rails一样用关键字参数声明一个方法。 some examples may be 一些例子可能是

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

How can I use symbols to create methods similar to the above? 如何使用符号创建类似于上述的方法?

I am very new to ruby. 我对红宝石很新。 Thanks in advance! 提前致谢!

Ruby doesn't actually have keyword arguments. Ruby实际上没有关键字参数。 Rails is exploiting a feature of Ruby which lets you omit the braces around a hash. Rails正在利用Ruby的一个功能,它可以省略哈希周围的大括号。 For example, with find , what we're really calling is: 例如,使用find ,我们真正称之为:

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

And then call it: 然后叫它:

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

Or call it without an argument, resulting in all default values being used: 或者在没有参数的情况下调用它,导致使用所有默认值:

explode

Since Ruby 2.0, ruby does have keyword arguments . 从Ruby 2.0开始,ruby 确实有关键字参数

def my_method(arg1, name: 'defaultName', number: 0)
  puts arg1, name, number
end

I agree with accepted answer given by Samir Talwar and christopherwright. 我同意Samir Talwar和christopherwright给出的公认答案。 The only potential downside is that you get no warnings if you use an incorrect keyword symbol as an argument or when looking up an option, it just ends up ignored. 唯一可能的缺点是,如果您使用不正确的关键字符号作为参数或查找选项时没有警告,它最终会被忽略。 If that's something you're concerned about, the gem hash_keyword_args addresses it. 如果这是你关心的事情,那么gem hash_keyword_args会解决它。 The idiom would be 这个成语是

def explode(opts={})
    opts = opts.keyword_args(:message => "Kabloooie!", :timer => 10, :count => 1)

    opts.count.times do
        sleep opts.timer
        puts opts.message
    end
end

Notice the use of accessor methods so you'll get a NoMethodError if you mistype a keyword. 请注意使用访问器方法,以便在输入关键字时输入NoMethodError。 And the calling behavior is: 调用行为是:

explode(:message => "Okay")   # works
explode(:msg => "Oops")       # raises ArgumentError

The gem also provides a few other features you might or might not care about, such as being able to indicate that a keyword is required. gem还提供了一些您可能或可能不关心的其他功能,例如能够指示需要关键字。 I've been using it happily for a while now. 我一直在愉快地使用它一段时间了。

(Disclaimer: I'm the author of the gem.) (免责声明:我是宝石的作者。)

You just need to define a method where one of the parameters is a hash. 您只需要定义一个方法,其中一个参数是哈希值。 It's actually pretty simple. 它实际上非常简单。

def method(arg1, params)
  name = params[:name]
  number = params[:number]

And then call it like: 然后把它称为:

method(arg1, :name => 'Eric', :number => 2)

Two notes: 两个笔记:

  1. In Ruby, you don't need to surround the parameters hash in {} when you call the method in most cases, unless you have something complicated going on like passing multiple hashes. 在Ruby中,在大多数情况下调用方法时,不需要在{}中包围参数哈希,除非你有一些复杂的事情,如传递多个哈希值。 In that case, make sure you surround those parameters with {} 在这种情况下,请确保用{}包围这些参数
  2. Ruby is dynamically typed, so you don't need to say that params is a hash when you define the method. Ruby是动态类型的,因此在定义方法时不需要说params是一个哈希值。

Since Ruby is typed dynamically, just do : 由于Ruby是动态输入的,所以只需:

def my_method(arg1, arg2)
  #things
end

example: 例:

my_method(:test, {:somehash => "yay"})

or 要么

my_method :test, :somehash => "yay"

or 要么

my_method(:test, :somehash => "yay")

Ruby 2.0 introduced real keyword arguments, and Ruby 2.1 added required keyword arguments. Ruby 2.0引入了真正的关键字参数,Ruby 2.1添加了必需的关键字参数。

There's a nice article up at https://chriszetter.com/blog/2012/11/02/keyword-arguments-in-ruby-2-dot-0/ on this, I've borrowed the examples from there: https://chriszetter.com/blog/2012/11/02/keyword-arguments-in-ruby-2-dot-0/上有一篇很好的文章,我从那里借用了这些例子:

Ruby 2.0+: Ruby 2.0+:

def exclaim(text, exclamation: '!', number: 7)
  text + exclamation * number
end

exclaim('hello', number: 4) #=> 'hello!!!!'

# equivalent:
exclaim('hello', {:number => 4}) #=> 'hello!!!!'

Ruby 2.1+: Ruby 2.1+:

def exclaim(text, exclamation: '!', number:)
  text + exclamation * number
end

exclaim('Yo', number: 5) # => 'Yo!!!!!'
exclaim('Yo') # raises: ArgumentError: missing keyword: number

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM