Ruby 2.0正在添加命名参数,如下所示:

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

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

如何在不提供默认值的情况下使用命名参数,以便它们是必需的?

推荐答案

Ruby 2.0.0中没有具体的方法,但是你可以使用can do it Ruby 2.1.0,语法像def foo(a:, b:) ...

在Ruby 2.0中.x、 可以通过放置引发异常的任何表达式来强制执行,例如:

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

如果你计划经常这样做(并且不能使用Ruby 2.1+),你可以使用一个助手方法,比如:

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相关问答推荐

指南针手表:未定义的方法存在吗?对于文件:类

ruby 中的魔术注释(#Encoding: utf-8)是如何工作的?

用于 ruby​​ gems 的新 10.9 OSX 的命令行工具?

在 Ruby 中生成一个后台进程

RSpec 是否有可能期望在两个表中发生变化?

检测安装的 CPU 数量

rbenv 没有显示可用的 ruby​​ 版本

jekyll 调试或打印所有变量

确定字符串数组是否包含ruby中的某个子字符串

来自 Linux 上的命令队列的并行处理(bash、python、ruby ......随便)

Ruby:继承与类变量一起工作的代码

array.include?多个值

就地修改 ruby​​ 哈希(rails strong params)

to_a 和 to_ary 有什么区别?

`respond_to?` 与 `respond_to_missing?`

Javascript 是否有类似 Ruby 的 method_missing 功能?

在 OSX 10.10 Yosemite 上安装 Nokogiri

将 CSV 文件转换为哈希数组

如何在 Ruby 中找到字符串中字符的索引?

为什么 Ruby setter 需要self .班级内的资格?