为什么 do/end 和 {} 并不总是等价的? [英] Why aren't do/end and {} always equivalent?
问题描述
可能的重复:
Ruby 块和非括号参数
有什么区别或价值Ruby 中的这些块编码样式?
我一直认为以下只是说同一件事的两种方式:
I always thought that the following are just two ways of saying the same thing:
[1,2,3].collect{|i| i * 2}
[1,2,3].collect do |i|
i * 2
end
但是我在我的一个 ERB 模板中发现了一些奇怪的行为,其中两种语法似乎做了两种不同的事情.此代码效果很好:
But I'm getting some weird behaviour in one of my ERB templates where the two syntaxes seem to do two different things. This code works great:
<%=raw @menu.collect { |m|
content_tag("li") {
link_to(m.capitalize, url_for(:controller => m))
}
} %>
但是当我把它改写为:
<%=raw @menu.collect do |m|
content_tag("li") do
link_to(m.capitalize, url_for(:controller => m))
end
end %>
...我最终得到的是@menu 项的连接字符串.我错过了什么吗?是否有一些细微的语法糖在这里挡住了路?
... I just end up with a concatenated string of my @menu items. Am I missing something? Is there some tiny grain of syntactic sugar getting in the way here?
推荐答案
我会使用您的第一种方法或将此代码放在视图助手中.但是如果我确实想使用块,我可能会做这样的事情.
I would use your first method or place this code in a view helper. But if I did want to use blocks I'd probably do something like this.
<% @menu.collect do |m| %>
<%= content_tag("li") do %>
<% link_to(m.capitalize, url_for(:controller => m)) %>
<% end %>
<% end %>
这篇关于为什么 do/end 和 {} 并不总是等价的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!