有一种简单的方法可以测试多个变量在ruby中具有相同的值吗?
有点像这样:
if a == b == c == d #does not work
#Do something because a, b, c and d have the same value
end
Run Code Online (Sandbox Code Playgroud)
当然可以针对主机检查每个变量以查看它们是否都是真的,但这是更多的语法并且不那么清楚.
if a == b && a == c && a == d #does work
#we have now tested the same thing, but with more syntax.
end
Run Code Online (Sandbox Code Playgroud)
你需要这样的东西的另一个原因是你在测试之前是否确实对每个变量都有效.
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
Run Code Online (Sandbox Code Playgroud)
Sha*_*cci 20
将它们全部扔进一个数组,看看是否只有一个唯一的项目.
if [a,b,c,d].uniq.length == 1
#I solve almost every problem by putting things into arrays
end
Run Code Online (Sandbox Code Playgroud)
正如sawa在评论中指出的那样.如果它们都是假的或者为零则失败.
module Enumerable
def all_equal?
each_cons(2).all? { |x, y| x == y }
end
end
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是表达我最清楚的方式.