gpt4 book ai didi

ruby-on-rails - 为什么erb block 连接 block 内容

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:19 25 4
gpt4 key购买 nike

我有以下代码:

require 'erb'

def body &block
content = block.call
content = block.call
content = block.call
content
end

x = 2
template = ERB.new <<-EOF
<% body do %>
2
<% end %>
EOF

template.run(binding)

当我执行它时输出 2 2 2。为什么每次调用 body 方法中的 block.call 时,它都会连接 block 的内容?

为什么如果我使用以下模板它不会发生:

template = ERB.new <<-EOF
<%= body do
2
end %>
EOF

我无法理解这里发生的事情。我在使用 Rails 时遇到了这个问题,但将代码隔离为纯 Ruby 以试图了解问题所在。

最佳答案

这是因为 ERB 的运作方式。参见 erb-generated ruby​​ source for your templates (template.src, below is prettified),对于前一个模板:

_erbout = +''
_erbout.<< " ".freeze
body do
_erbout.<< "\n 2\n ".freeze # <<-- this is the line that produces extra output
end
_erbout.<< "\n".freeze
_erbout

对于后者:

_erbout = +''
_erbout.<< " ".freeze
_erbout.<<(( body do
2 # <<- and this time it is just plain ruby code
end
).to_s)
_erbout.<< "\n".freeze
_erbout

注意在运行时如何阻止输出到同一个缓冲区。

实际上这是正常的并且被广泛使用,例如,对于传递给 each 方法的下面的 block ,您希望将每次运行的输出连接起来:

<% @items.each do |item| %>
Item <%= item %>
<% end %>

关于ruby-on-rails - 为什么erb block 连接 block 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56793764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com