本文介绍了我可以要求在Ruby中2.x的命名参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

红宝石2.0是添加一个名为参数,就像这样:

Ruby 2.0 is adding named parameters, like this:

def say(greeting: 'hi')
  puts greeting
end

say                     # => puts 'hi'
say(greeting: 'howdy')  # => puts 'howdy'

我如何使用命名参数没有给一个默认值,因此它们需要?

How can I use named parameters without giving a default value, so that they are required?

推荐答案

有是用Ruby 2.0.0没有具体的办法,但你的,像语法高清美孚(A:,b :) ...

There is no specific way in Ruby 2.0.0, but you can do it Ruby 2.1.0, with syntax like def foo(a:, b:) ...

在红宝石2.0.x中,您可以通过将任何Ex pression抛出一个异常,例如强制执行:

In Ruby 2.0.x, you can enforce it by placing any expression raising an exception, e.g.:

def say(greeting: raise "greeting is required")
  # ...
end

如果你打算做这个有很多(且不能使用Ruby 2.1 +),你可以像使用一个辅助方法:

If you plan on doing this a lot (and can't use Ruby 2.1+), you could use a helper method like:

def required
  method = caller_locations(1,1)[0].label
  raise ArgumentError,
    "A required keyword argument was not specified when calling '#{method}'"
end

def say(greeting: required)
  # ...
end

say # => A required keyword argument was not specified when calling 'say'

这篇关于我可以要求在Ruby中2.x的命名参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:26