3

I read through the ruby docs examples but I'm still not sure what is happening in this code:

sentence = "How are you?"
sentence.chars.reduce do |memo, char|
    %w[a e i o u y].include?(char) ? memo + char * 5 : memo + char
end

What is the memo when the block of code is first executed? What do the subsequent 5 steps look like?

4

1 回答 1

6

由于您没有为 提供默认值reduce,因此它将设置memo为 中的第一个值sentence.chars,即"H".

迭代#1:

  • memo"H"
  • char"o"
  • 块的结果是"Hooooo"

然后将第一次迭代的结果作为第一个参数传递到块中。所以在第 2 次迭代中:

  • memo"Hooooo"
  • char"w"
  • 块的结果是"Hooooow"

这将针对数组的每个元素继续进行,最终结果将是块应用于最后一个元素后的结果。

一个简单的方法来查看它的实际效果是执行以下代码:

sentence = "How are you?"
sentence.chars.reduce do |memo, char|
  puts "Memo = #{memo}, char = #{char}"
  %w[a e i o u y].include?(char) ? memo + char * 5 : memo + char
end
于 2012-09-02T23:56:47.747 回答