在Ruby中执行类似“Sentences.each.each”的最干净的方法

时间:2011-11-22 16:02:28

标签: ruby loops coding-style each

假设我有一系列句子:

a = ["I love pie", "I love you more and more each day", "every day is a good day"]

我想测试句子中的每个单词。因为红宝石太棒了我以为a.each.each可能有用,但事实并非如此。有没有一个干净的方法,而不必在每个内部嵌套每个?

2 个答案:

答案 0 :(得分:5)

a.each { |sentence| sentence.split.each { |word| # do something with the word } }

或稍长的格式如果:

a.each do |sentence|
  sentence.split.each do |word|
    # do something
    # do something
    # do something
  end
end

答案 1 :(得分:2)

如果您想避免嵌套(至少在视觉上),您可以使用:

a.map(&:split).flatten.each{ |word| # do something }