我有一个选项散列和更新它的方法——但是选项散列可能会改变,如果改变了,我希望我的测试失败。什么是写这个的好方法?
raise RuntimeError, msg unless options.keys.include?(
:external_uid,
:display_name,
:country_code
)
如果 options.keys
不完全包含这三项,则应引发错误。
我几乎使用的解决方案(感谢 bjhaid):
def ensure_correct_options!(options)
msg = "Only 'external_uid', 'display_name' and 'country_code' can be "
msg += "updated. Given attributes: #{options.keys.inspect}"
raise RuntimeError, msg unless options.keys == [
:external_uid,
:display_name,
:country_code
]
end
最佳答案
选项可能有一个值,所以我会写:
unless options[:external_uid] && options[:display_name] && options[:country_code]
raise ArgumentError, ":external_uid, :display_name and :country_code required"
end
(我用 ArgumentError
替换了 RuntimeError
因为这似乎是关于参数的)
关于ruby - 检查数组中是否包含多个项目的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23060022/