问题描述
我可以生成code几行,将做到这一点,但我不知道是否有这样做的很好的清洁Rubyesque方式。如果我尚未明确,我要找的是一个数组方法,如果考虑到将返回true(说) [3,3,3,3,3]
或 [兔子,兔子,兔子]
,但将返回false与 [1,2,3,4,5 ]
或 [兔子,兔子,野兔]
。
感谢
类Array
高清same_values?
self.uniq.length == 1
结束
结束
[1,1,1,1] .same_values?
[1,2,3,4] .same_values?
这一个呢?它空数组返回false不过,你可以改变它为< = 1,它会在这种情况下返回true。根据你所需要的。
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"]
.
Thanks
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.
这篇关于如何测试,如果数组中的所有项目都是相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!