测试多个变量是否具有相同值的简单方法,ruby

时间:2021-09-18 00:45:07

Is there a simple way of testing that several variables have the same value in ruby?

有一种简单的方法可以测试多个变量在ruby中具有相同的值吗?

Something linke this:

有点像这样:

if a == b == c == d #does not work
   #Do something because a, b, c and d have the same value
end

Of course it is possible to check each variable against a master to see if they are all true, but that is a bit more syntax and is not as clear.

当然,可以针对主设备检查每个变量以查看它们是否都是真的,但这是更多的语法并且不那么清楚。

if a == b && a == c && a == d #does work
    #we have now tested the same thing, but with more syntax.
end

Another reason why you would need something like this is if you actually do work on each variable before you test.

您需要这样的东西的另一个原因是,如果您在测试之前确实对每个变量进行了操作。

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

5 个解决方案

#1


19  

Throw them all into an array and see if there is only one unique item.

将它们全部扔进一个数组,看看是否只有一个唯一的项目。

if [a,b,c,d].uniq.length == 1
  #I solve almost every problem by putting things into arrays
end

As sawa points out in the comments .one? fails if they are all false or nil.

正如sawa在评论中指出的那样。如果它们都是假的或者为零则失败。

#2


5  

tokland suggested a very nice approach in his comment to a similar question:

托克兰在对类似问题的评论中提出了一个非常好的方法:

module Enumerable
  def all_equal?
    each_cons(2).all? { |x, y| x == y }
  end
end

It's the cleanest way to express this I've seen so far.

到目前为止,这是表达我最清楚的方式。

#3


2  

How about:

怎么样:

[a,b,c,d] == [b,c,d,a]

Really just:

真的只是:

[a,b,c] == [b,c,d]

will do

会做

#4


2  

a = [1,1,1]
(a & a).size == 1 #=> true

a = [1,1,2]
(a & a).size == 1 #=> false

#5


1  

[b, c, d].all?(&a.method(:==))

#1


19  

Throw them all into an array and see if there is only one unique item.

将它们全部扔进一个数组,看看是否只有一个唯一的项目。

if [a,b,c,d].uniq.length == 1
  #I solve almost every problem by putting things into arrays
end

As sawa points out in the comments .one? fails if they are all false or nil.

正如sawa在评论中指出的那样。如果它们都是假的或者为零则失败。

#2


5  

tokland suggested a very nice approach in his comment to a similar question:

托克兰在对类似问题的评论中提出了一个非常好的方法:

module Enumerable
  def all_equal?
    each_cons(2).all? { |x, y| x == y }
  end
end

It's the cleanest way to express this I've seen so far.

到目前为止,这是表达我最清楚的方式。

#3


2  

How about:

怎么样:

[a,b,c,d] == [b,c,d,a]

Really just:

真的只是:

[a,b,c] == [b,c,d]

will do

会做

#4


2  

a = [1,1,1]
(a & a).size == 1 #=> true

a = [1,1,2]
(a & a).size == 1 #=> false

#5


1  

[b, c, d].all?(&a.method(:==))