Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 检查数组中是否包含多个项的好方法_Ruby_Arrays - Fatal编程技术网

Ruby 检查数组中是否包含多个项的好方法

Ruby 检查数组中是否包含多个项的好方法,ruby,arrays,Ruby,Arrays,我有一个选项散列和一个更新它的方法——但是选项散列可能会改变,如果改变了,我希望我的测试失败。写这个的好方法是什么 raise RuntimeError, msg unless options.keys.include?( :external_uid, :display_name, :country_code ) 如果options.keys不完全包括这三项,则应引发错误 我几乎使用的解决方案(谢谢): 这些选项可能有一个值,所以我会写: unless options[:exter

我有一个选项散列和一个更新它的方法——但是选项散列可能会改变,如果改变了,我希望我的测试失败。写这个的好方法是什么

raise RuntimeError, msg unless options.keys.include?(
  :external_uid,
  :display_name,
  :country_code
)
如果
options.keys
不完全包括这三项,则应引发错误

我几乎使用的解决方案(谢谢):


这些选项可能有一个值,所以我会写:

unless options[:external_uid] && options[:display_name] && options[:country_code]
  raise ArgumentError, ":external_uid, :display_name and :country_code required"
end

(我已经用
ArgumentError
替换了
RuntimeError
,因为这似乎是关于参数的)

选项可能有一个值,所以我要写:

unless options[:external_uid] && options[:display_name] && options[:country_code]
  raise ArgumentError, ":external_uid, :display_name and :country_code required"
end

(我已将
RuntimeError
替换为
ArgumentError
,因为这似乎与参数有关)

如果有三个以上的值要测试是否包含在哈希中作为键,您可能会这样做:

unless ([:external_uid, :display_name,...] - options.keys).empty? \
  raise ArgumentError, ":external_uid, :display_Nam,... are required"

如果有三个以上的值要测试是否包含为哈希中的键,您可能会这样做:

unless ([:external_uid, :display_name,...] - options.keys).empty? \
  raise ArgumentError, ":external_uid, :display_Nam,... are required"

也许这个答案会有帮助。@Magnuss,干杯,我看到了,但我只想要精确的匹配……我最终选择了一个更简单的解决方案。cheers@dax,您的解决方案将失败,如果数组中的元素以不同的方式排序,请查看其行为是否接近您想要的,但在单键上,Wow,good point@bjhaidMaybe-answer可能会有所帮助。@Magnuss,干杯,我看到了,但我只想要精确的匹配…我最终选择了一个更简单的解决方案。cheers@dax,您的解决方案将失败,如果数组中的元素以不同的方式排序,请查看其行为是否接近您想要的,但是在单个keyswow上,good point@bjhaid
options.key(…)和&(…
可能更可取,因为我们不知道哈希中是否允许
nil
值。
options.key(…)&&&…
可能更可取,因为我们不知道哈希中是否允许
nil
值。