%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
在 ruby 中,{|args| statements} 叫做 匿名函数,就是没有名字的小型函数。然后 each_byte 是一个方法,它接收一个可调用对象。有时候左花括号可以用 do 代替,有花括号用 end 代替,就是
do |args|
statements
end
这种形式。