Возможно решение, которое следует вашему исходному коду:
a = "Apple Banana oranges grapes. free free free phones. deals deals time.black white grey"
b = a.split(/\W+/)
c = 0
d = 0
g = Array.new
t = Array.new
b.each do |i|
if i == "free"
t.push i
c = c + 1
elsif i == "deals"
t.push i
d = d + 1
else
g.push i
end
end
puts "Original words: #{b}"
puts "Counts of 'free': #{c}"
puts "Counts of 'deals': #{d}"
puts "Array of matches: #{t}"
puts "Array of non matches: #{g}"
И вывод:
# Original words: ["Apple", "Banana", "oranges", "grapes", "free", "free", "free", "phones", "deals", "deals", "time", "black", "white", "grey"]
# Counts of 'free': 3
# Counts of 'deals': 2
# Array of matches: ["free", "free", "free", "deals", "deals"]
# Array of non matches: ["Apple", "Banana", "oranges", "grapes", "phones", "time", "black", "white", "grey"]
Пример подсчета с использованием инструментов Ruby:
counts = {}
a.split(/\W+/).tap { |b| b.uniq.map { |w| counts[w.downcase] = b.count(w) } }
counts #=> {"apple"=>1, "banana"=>1, "oranges"=>1, "grapes"=>1, "free"=>3, "phones"=>1, "deals"=>2, "time"=>1, "black"=>1, "white"=>1, "grey"=>1}
Затем вы можете получить доступ к данным, например:
counts.keys #=> ["apple", "banana", "oranges", "grapes", "free", "phones", "deals", "time", "black", "white", "grey"]
counts['free'] #=> 3
counts['deals'] #=> 2
counts.select { |_, v| v > 1} #=> {"free"=>3, "deals"=>2}