Simplifying an “any of” check with or-operator in Ruby

末鹿安然 提交于 2019-12-10 15:25:51

问题


How to simplify the following check ?...

if node[:base][:database][:adapter].empty? || node[:base][:database][:host].empty? || 
  node[:base][:database][:database].empty? || node[:base][:database][:port].empty? 

to something like

required_keys = { :adapter, :host, :database...etc...} 
required keys - node[:base][:database] == [] 

This syntax is a little off, but basically subtract the keys you have from the set of required keys. If you have all the required keys in your set, the result should be empty.

I am not sure regarding the correct syntax ? . Any help would be appreciated


回答1:


required_keys = [:adapter, :host, :database ]
if required_keys.any?{|x| node[:base][:database][x].empty?}
  #code here
end

Or you could do also:

node[:base][:database].values_at(*required_keys).any?(&:empty?) 



回答2:


If you think you're going to use this functionality multiple places, you can extend the Hash class and require the extension in an initializer.

class Hash

  def contains_values_for?(*keys)
    keys.all? do |key|
      self[key].present?
    end
  end

end

Now you can do:

node[:base][:database].contains_values_for?(:adapter, :host, :database, :port)


来源:https://stackoverflow.com/questions/16574162/simplifying-an-any-of-check-with-or-operator-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!