I can generate a few lines of code that will do this but I'm wondering if there's a nice clean Rubyesque way of doing this. In case I haven't been clear, what I'm looking for is an array method that will return true if given (say) [3,3,3,3,3]
or ["rabbits","rabbits","rabbits"]
but will return false with [1,2,3,4,5]
or ["rabbits","rabbits","hares"]
.
我可以生成几行代码来做这个但我想知道是否有一个干净的Rubyesque方法。如果我还不清楚,我要找的是一个数组方法,如果给定(比方说)[3,3,3,3,3]或["兔子","兔子","兔子"],但将返回false,但将返回false,[1,2,3,4,5]或["兔子","兔子","兔子"]。
Thanks
谢谢
5 个解决方案
#1
58
class Array
def same_values?
self.uniq.length == 1
end
end
[1, 1, 1, 1].same_values?
[1, 2, 3, 4].same_values?
What about this one? It returns false for an empty array though, you can change it to <= 1 and it will return true in that case. Depending on what you need.
这一个怎么样?对于空数组,它返回false,您可以将它更改为<= 1,在这种情况下,它将返回true。这取决于你需要什么。
#2
68
You can use Enumerable#all?
which returns true if the given block returns true for all the elements in the collection.
您可以使用可列举的# ?如果给定的块对集合中的所有元素返回true,则返回true。
array.all? {|x| x == array[0]}
(If the array is empty, the block is never called, so doing array[0]
is safe.)
(如果数组为空,则不会调用该块,因此使用数组[0]是安全的。)
#3
9
I too like preferred answer best, short and sweet. If all elements were from the same Enumerable class, such as Numeric or String, one could use
我也喜欢最好的、简短的和甜蜜的回答。如果所有元素都来自相同的可枚举类,例如数字或字符串,则可以使用
def all_equal?(array) array.max == array.min end
#4
1
I used to use :
我曾经用过:
def add_equal?(arr) arr.reduce { |x,y| x == y ? x : nil } end
It may fail when arr
contains nil
.
当arr包含nil时,它可能会失败。
#5
1
I would use:
我将使用:
array = ["rabbits","rabbits","hares", nil, nil]
array.uniq.compact.length == 1
#1
58
class Array
def same_values?
self.uniq.length == 1
end
end
[1, 1, 1, 1].same_values?
[1, 2, 3, 4].same_values?
What about this one? It returns false for an empty array though, you can change it to <= 1 and it will return true in that case. Depending on what you need.
这一个怎么样?对于空数组,它返回false,您可以将它更改为<= 1,在这种情况下,它将返回true。这取决于你需要什么。
#2
68
You can use Enumerable#all?
which returns true if the given block returns true for all the elements in the collection.
您可以使用可列举的# ?如果给定的块对集合中的所有元素返回true,则返回true。
array.all? {|x| x == array[0]}
(If the array is empty, the block is never called, so doing array[0]
is safe.)
(如果数组为空,则不会调用该块,因此使用数组[0]是安全的。)
#3
9
I too like preferred answer best, short and sweet. If all elements were from the same Enumerable class, such as Numeric or String, one could use
我也喜欢最好的、简短的和甜蜜的回答。如果所有元素都来自相同的可枚举类,例如数字或字符串,则可以使用
def all_equal?(array) array.max == array.min end
#4
1
I used to use :
我曾经用过:
def add_equal?(arr) arr.reduce { |x,y| x == y ? x : nil } end
It may fail when arr
contains nil
.
当arr包含nil时,它可能会失败。
#5
1
I would use:
我将使用:
array = ["rabbits","rabbits","hares", nil, nil]
array.uniq.compact.length == 1