我喜欢红宝石块!它们背后的想法非常非常简洁和方便。
我刚刚回顾了过去一周左右的代码,基本上是我写过的每一个 ruby 函数,而且我注意到它们中没有一个返回值!我总是使用块来传回数据,而不是返回值!
我什至发现自己正在考虑编写一个小状态类,这将允许我编写如下代码:
something.do_stuff do |status|
status.success do
# successful code
end
status.fail do
# fail code
puts status.error_message
end
end
我是否使用了过多的块?是否有时使用块,有时使用返回值?
有什么需要注意的问题吗?我对方块的大量使用是否会在某个时候来咬我?
整个事情将更具可读性:
if something.do_stuff
#successful code
else
#unsuccessful code
end
或者使用共轨惯用法:
if @user.save
render :action=>:show
else
@user.errors.each{|attr,msg| logger.info "#{attr} - #{msg}" }
render :action=>:edit
end
恕我直言,避免返回布尔值是过度使用代码块。
如果 ,则块有意义。 。 。
它允许代码使用资源而无需关闭该资源
open("fname") do |f|
# do stuff with the file
end #don't have to worry about closing the file
调用代码必须对结果进行重要的计算
在这种情况下,您可以避免将返回值添加到调用范围。这对于多个返回值通常也是有意义的。
something.do_stuff do |res1, res2|
if res1.foo? and res2.bar?
foo(res1)
elsif res2.bar?
bar(res2)
end
end #didn't add res1/res2 to the calling scope
代码必须在yield之前和之后调用
您可以在一些 Rails 助手中看到这一点:
<% content_tag :div do %>
<%= content_tag :span "span content" %>
<% end -%>
而且当然迭代器是一个很好的用例,因为它们(被红宝石主义者认为)比for
循环或列表推导式 http://en.wikipedia.org/wiki/List_comprehension.
当然不是一个详尽的列表,但我建议您不要只使用块,因为您可以。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)