Augustin Riedinger Augustin Riedinger - 1 year ago 195
Ruby Question

Ruby best practice : if not empty each do else in one operator

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


I'd like to have one loop, without writing
array
twice. I read this, but there is no solution good enough.




2.
I am actually in an HAML template. Same question.

- if array.empty?
%p No result
- else
%ul
- array.each do |el|
%li el

Answer Source

What about?

array.each do |x|
  #...
  puts "x",x
end.empty? and begin
  puts "empty!"
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download