红宝石中的三向比较

时间:2012-10-11 18:19:55

标签: ruby

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

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

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

3 个答案:

答案 0 :(得分:13)

三个要素最简洁的方法是(抱歉让你失望):

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

答案 1 :(得分:3)

dog == cat && dog == chicken

答案 2 :(得分:0)

给出数字比较:

dog ='animal'

cat ='animal'

chicken ='animal'

shoe ='clothing'

创建一个数组:

b