How to compress multi-identical conditions in a statement using Ruby?

Viewed 43

Here is what I did:

output = "xyz"
result = false

unless output == "" || output.nil? || output == "{}" || result == true
  puts 'execute this command'
end

What could be the simplest format to shrink the above statement, if there is a similar || conditions in Ruby

2 Answers

In versions of Ruby 2.5 and above you can use #any? this way:

['', nil, '{}'].any?(output) || result

p ['', nil, '{}'].any?('')   # true
p ['', nil, '{}'].any?(nil)  # true
p ['', nil, '{}'].any?('{}') # true

Otherwise, you can use a block

['', nil, '{}'].any? { |e| e == output }

Something like this?

unless ["", nil, "{}"].include?(output) || result
  puts 'execute this command'
end
Related