What's the most concise way to ensure three variables are all equal in ruby? For example
dog = 'animal'
cat = 'animal'
chicken = 'animal'
shoe = 'clothing'
# Something like this...which doesn't work
dog == cat == chicken # true
dog == cat == shoe # false
The most concise way for three elements is (sorry to disappoint you):
dog == cat && cat == chicken
Of course you can always get clever if you want to...
[dog, cat, chicken] == [dog] * 3
[dog, cat, chicken].uniq.length == 1
...but that doesn't really make the code more concise (or readable).
I would do something like this if you want a reusable function that can compare arbitrarily many elements for equality:
def all_equal?(*elements)
elements.all? { |x| x == elements.first }
end
dog == cat && dog == chicken
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With