确保红宝石中三个变量都相等的最简洁方法是什么?例如
dog = 'animal'
cat = 'animal'
chicken = 'animal'
shoe = 'clothing'
# Something like this...which doesn't work
dog == cat == chicken # true
dog == cat == shoe # false
确保红宝石中三个变量都相等的最简洁方法是什么?例如
dog = 'animal'
cat = 'animal'
chicken = 'animal'
shoe = 'clothing'
# Something like this...which doesn't work
dog == cat == chicken # true
dog == cat == shoe # false
三个元素最简洁的方式是(抱歉让你失望了):
dog == cat && cat == chicken
当然,如果你愿意,你总是可以变得聪明......
[dog, cat, chicken] == [dog] * 3
[dog, cat, chicken].uniq.length == 1
...但这并没有真正使代码更简洁(或可读)。
如果您想要一个可以比较任意多个元素是否相等的可重用函数,我会做这样的事情:
def all_equal?(*elements)
elements.all? { |x| x == elements.first }
end
dog == cat && dog == chicken
给定数字进行比较:
狗='动物'
猫='动物'
鸡='动物'
鞋='衣服'
创建一个数组:
arr = [dog, cat, chicken, shoe]
arr_length = arr.reject { |a| a != dog }.length
if arr_length == 0
puts "All numbers are equal"
end