是否有一种简单的方法可以测试几个变量在 ruby 中具有相同的值?
一些东西链接这个:
if a == b == c == d #does not work
#Do something because a, b, c and d have the same value
end
当然,可以根据主控检查每个变量,看看它们是否都是真的,但这有点更多的语法并且不是那么清楚。
if a == b && a == c && a == d #does work
#we have now tested the same thing, but with more syntax.
end
您需要这样的东西的另一个原因是,如果您在测试之前确实对每个变量进行了处理。
if array1.sort == array2.sort == array3.sort == array4.sort #does not work
#This is very clear and does not introduce unnecessary variables
end
#VS
tempClutter = array1.sort
if tempClutter == array2.sort && tempClutter == array3.sort && tempClutter == array4.sort #works
#this works, but introduces temporary variables that makes the code more unclear
end