Ruby最佳实践:如果不为空,则在一个运算符中执行其他操作 [英] Ruby best practice : if not empty each do else in one operator
本文介绍了Ruby最佳实践:如果不为空,则在一个运算符中执行其他操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
1.我找不到一种编写此代码的优雅方法:
1.I can't find an elegant way to write this code:
if array.empty?
# process empty array
else
array.each do |el|
# process el
end
end
我希望有一个循环,而不必两次编写array
.我阅读了这,但是没有足够好的解决方案.
I'd like to have one loop, without writing array
twice. I read this, but there is no solution good enough.
2. 我实际上在HAML模板中.同样的问题.
2. I am actually in an HAML template. Same question.
- if array.empty?
%p No result
- else
%ul
- array.each do |el|
%li el
推荐答案
那又如何?
array.each do |x|
#...
puts "x",x
end.empty? and begin
puts "empty!"
end
这篇关于Ruby最佳实践:如果不为空,则在一个运算符中执行其他操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文