如何用ruby统计数组或哈希中不同元素的个数

Python014

如何用ruby统计数组或哈希中不同元素的个数,第1张

得到不同数据的值:

%w(a b c a c d).uniq

得到各个元素出现的个数:

count_hash = {}

%w(a b c a c d).each do |item|

key = item.to_sym

if count = count_hash[key]

count_hash[key] = count + 1

else

count_hash[key] = 1

end

end

返回第一个元件,或第一元素,可枚举的。如果枚举是空的,第一种形式返回nil ,而第二种形式返回一个空数组

%w[foo bar baz].first #=>"foo"

%w[foo bar baz].first(2) #=>["foo", "bar"]

%w[foo bar baz].first(10) #=>["foo", "bar", "baz"]

[].first #=>nil