嵌套块和ERB

时间:2014-12-20 20:41:13

标签: ruby block erb yield

对于我的生活,我无法弄清楚为什么这不能按预期工作。

代码:

require 'erb'

def say_hello(name)
  "Nice to see you, #{ name }!"
end

def greetings
  template = <<-TEMPLATE
Hello!
<%= yield %>
Goodbye!
  TEMPLATE
  ERB.new(template).result(binding)
end

people = ['Aaron', 'Bob', 'Tim', 'Juan']
t = greetings do
  people.each do |p|
    say_hello(p)
  end
end

puts t

(我知道,有点做作,但这是有用的。)

我的期望:

Hello!
Nice to see you, Aaron!
Nice to see you, Bob!
Nice to see you, Tim!
Nice to see you, Juan!
Goodbye!

我得到了什么:

Hello!
['Aaron', 'Bob', 'Tim', 'Juan']
Goodbye!

思想:

我猜这种情况正在发生,因为内部块(以people.each开头)在块执行之前被强制转换为字符串。也许ERB不喜欢我如何尝试将新的构造文本块注入其模板中。

这里发生了什么?

1 个答案:

答案 0 :(得分:2)

each的返回值是数组本身,而不是块的返回值:

people.each do |p|
  say_hello(p)
end
# => ['Aaron', 'Bob', 'Tim', 'Juan']

您应该使用map,它返回块中返回值的数组:

people.map do |p|
  say_hello(p)
end
# => ["Nice to see you, Aaron!", "Nice to see you, Bob!", "Nice to see you, Tim!", "Nice to see you, Juan!"]

您还需要连接数组以正确呈现它:

t = greetings do
  people.map do |p|
    say_hello(p)
  end.join("\n")
end