问题
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