问题描述
我有这样的阵列,例如(大小可变):
X = [1.111,1.122,1.250,1.111]
和我需要找到(在这种情况下,1.111
)的最黎民值。
有没有一种简单的方法来做到这一点?
韩国社交协会提前!
结果
修改#1:谢谢大家的答案
结果
修改#2:基于Z.E.D.的信息,我已经改变了我接受的答案。再次谢谢大家!
红宝石< 2.2
#!的/ usr / bin中/ ruby1.8的高清most_common_value(一)
a.group_by做| E |
Ë
end.values.max_by(安培;:大小)。首先
结束X = [1.111,1.122,1.250,1.111]
p most_common_value(X)#=> 1.111
请注意: Enumberable.max_by
是新的使用Ruby 1.9,但它已被反向移植到1.8.7
红宝石> = 2.2
红宝石2.2引入了的方法,与我们可以使code更简洁:
DEF most_common_value(一)
a.group_by(安培;:本身).values.max_by(安培;:大小)。首先
结束
作为一个猴补丁
或者像可枚举#模式
:
Enumerable.class_eval做
高清模式
GROUP_BY做| E |
Ë
end.values.max_by(安培;:大小)。首先
结束
结束[1.111,1.122,1.250,1.111。模式
#=> 1.111
I have this array, for example (the size is variable):
x = ["1.111", "1.122", "1.250", "1.111"]
and I need to find the most commom value ("1.111"
in this case).
Is there an easy way to do that?
Tks in advance!
EDIT #1: Thank you all for the answers!
EDIT #2: I've changed my accepted answer based on Z.E.D.'s information. Thank you all again!
Ruby < 2.2
#!/usr/bin/ruby1.8
def most_common_value(a)
a.group_by do |e|
e
end.values.max_by(&:size).first
end
x = ["1.111", "1.122", "1.250", "1.111"]
p most_common_value(x) # => "1.111"
Note: Enumberable.max_by
is new with Ruby 1.9, but it has been backported to 1.8.7
Ruby >= 2.2
Ruby 2.2 introduces the Object#itself method, with which we can make the code more concise:
def most_common_value(a)
a.group_by(&:itself).values.max_by(&:size).first
end
As a monkey patch
Or as Enumerable#mode
:
Enumerable.class_eval do
def mode
group_by do |e|
e
end.values.max_by(&:size).first
end
end
["1.111", "1.122", "1.250", "1.111"].mode
# => "1.111"
这篇关于发现最常见的字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!