我有:
@fruit = ["Apples, Oranges, Bananas", "Apples", "Bananas, Pears", "Bananas, Apples, Pears", "Pears"]
我想用它做两件事,先把它变成一个纯数组,每个只有一个实例:
["Apples", "Oranges", "Bananas", "Pears"]
其次,我希望能够确定数组中给定实例的数量:
@fruit.count("Apples") = 3
第三,是否可以按实例数量对数组进行排序:
@fruit.sort = ["Apples", "Apples", "Apples", "Bananas", "Bananas", "Bananas", "Pears", "Pears", "Pears", "Oranges"]
我必须使用哪些数组/字符串函数来执行此操作?
答案 0 :(得分:6)
arr = ["Apples, Oranges, Bananas", "Apples", "Bananas, Pears", "Bananas, Apples, Pears", "Pears"]
hsh = Hash.new { |h, k| h[k] = 0 }
arr.each do |str|
fruits = str.split(/, /)
fruits.each do |fruit|
hsh[fruit] += 1
end
end
p hsh.keys
# => ["Apples", "Oranges", "Bananas", "Pears"]
hsh.keys.each { |fruit| puts "#{fruit}: #{hsh[fruit]}" }
# => Apples: 3
# => Oranges: 1
# => Bananas: 3
# => Pears: 3
答案 1 :(得分:4)
@fruit = ["Apples, Oranges, Bananas", "Apples", "Bananas, Pears", "Bananas, Apples, Pears", "Pears"]
@fruits = @fruit.map{|f| f.split(", ")}.flatten
#=>["Apples", "Oranges", "Bananas", "Apples", "Bananas", "Pears", "Bananas", "Apples", "Pears", "Pears"]
@fruits.uniq
#=> ["Apples", "Oranges", "Bananas", "Pears"]
@fruits.count{|f| f=="Apples"}
#=>3
答案 2 :(得分:2)
哈希是更好的数据结构:
@fruit = ["Apples, Oranges, Bananas", "Apples", "Bananas, Pears", "Bananas, Apples, Pears", "Pears"]
h = Hash.new
@fruit.each do |str|
str.split(/,/).each do |f|
f.strip!
h[f] ||= 0
h[f] += 1
end
end
h.keys
=> ["Apples", "Oranges", "Bananas", "Pears"]
h
=> {"Apples"=>3, "Oranges"=>1, "Bananas"=>3, "Pears"=>3}
h["Apples"]
=> 3
然后,您可以处理哈希中的累积数据,以便在需要时打印出已排序的数组。
答案 3 :(得分:0)
@fruit = ["Apples, Oranges, Bananas", "Apples", "Bananas, Pears", "Bananas, Apples, Pears", "Pears"]
p @fruit.map{|f| f.split(', ') }.flatten.uniq
#=> ["Apples", "Oranges", "Bananas", "Pears"]
p @fruit.count{|f| f.include?("Apples")}
#=> 3