如何测试,如果数组中的所有项目都是相同? [英] How do I test if all items in an array are identical?

查看:129
本文介绍了如何测试,如果数组中的所有项目都是相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以生成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.

这篇关于如何测试,如果数组中的所有项目都是相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆