如何遍历数组中的多个字符串

时间:2018-11-28 00:12:58

标签: arrays ruby string

我有一个字符串数组。

a = "Apple Banana oranges grapes. free free free phones. deals deals time.black white grey"
b = a.split(/\./)

我想检查每个字符串中是否存在单词"free""deals",并计数并将其存储到新数组中。

c = 0
d = 0
g = Array.new
t = Array.new
b.each do |i|
  if /free/.match(i)
    t.push i
    c = c + 1
  elsif /deals/.match(i)
    t.push i
    d = d + 1
  else
    g.push i
  end
end
p d
p c
p g
p t

但是它没有显示确切的计数。还有其他方法可以解析数组中的字符串吗?

3 个答案:

答案 0 :(得分:0)

稍微重命名变量,加上一些import * as BooksAPI from '../BooksAPI' 而不是匹配的技巧,这可能行得通吗?

scan

答案 1 :(得分:0)

您的方法计算的是句子,而不是匹配的句子中单词的出现。使用c += i.split.count "free"来计算单词"free"的实际出现次数。除非含义清楚,否则避免使用单字母变量名称。

但是,这一切似乎都有些多余。您可以使用builtin array methods执行计数并选择/拒绝与模式匹配的项目:

a = "Apple Banana oranges grapes. free free free phones. deals deals time.black white grey"

p a.split(".").grep /\bfree\b|\bdeals\b/
p a.split(".").reject {|e| e =~ /\bfree\b|\bdeals\b/}
p a.split.count "free"
p a.split.count "deals"

输出:

[" free free free phones", " deals deals time"]
["Apple Banana oranges grapes", "black white grey"]
3
2

Try it!

答案 2 :(得分:0)

可能是遵循原始代码的解决方案:

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}