分享 发现一个很有意思的写法

kikyous · 2016年01月13日 · 最后由 xlaok 回复于 2016年05月06日 · 2904 次阅读
<% if @messages.each do |message| %>
  <%# code or partial to display the message %>
<% end.empty? %>
  You have no messages.
<% end %>

写成这样好理解一点

<% if @messages.each{|message| 'code or partial to display the message' }.empty? %>
  You have no messages.
<% end %>

这样可以少一层 block,这是什么项目里看到的?

#2 楼 @rei 不是项目里面看到的,我突然脑洞大开,写了个

each
else
end

发现不行,就去 google 了一下 http://stackoverflow.com/questions/1027871/rails-an-elegant-way-to-display-a-message-when-there-are-no-elements-in-databas

有个缺点是用不到 multi fetch cache 优化了。

我也是醉了

短路大法好 当年刚学会写短路的时候,php 一行里面 3 个短路,真的是用得丧心病狂。转 ruby 后,if / unless 太好用,也就用得不多了 我也来分享一个: ruby 中使用短路有个很大的便利, &&(或 ||)后面可以直接接 return

render(text: 'No, no, no, U cannot see me') && return

这是短路一个很合适的运用,但是这一点在 php 和 js 里面都是不行的,这两种语言里 return 需要换行写,大 RUBY 就是 diao

需要 登录 后方可回复, 如果你还没有账号请 注册新账号