10

确保红宝石中三个变量都相等的最简洁方法是什么?例如

dog = 'animal'
cat = 'animal'
chicken = 'animal'
shoe = 'clothing'

# Something like this...which doesn't work
dog == cat == chicken # true   
dog == cat == shoe # false
4

3 回答 3

19

三个元素最简洁的方式是(抱歉让你失望了):

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
于 2012-10-11T18:23:29.677 回答
3
dog == cat && dog == chicken
于 2012-10-11T18:23:00.500 回答
0

给定数字进行比较:

狗='动物'

猫='动物'

鸡='动物'

鞋='衣服'

创建一个数组:

arr = [dog, cat, chicken, shoe]
arr_length = arr.reject { |a| a != dog }.length

if arr_length == 0
puts "All numbers are equal"
end  
于 2018-01-04T12:39:56.060 回答