Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 507
Augustin Riedinger Avatar asked May 31 '13 15:05

Augustin Riedinger


1 Answers

What about?

array.each do |x|   #...   puts "x",x end.empty? and begin   puts "empty!" end 
like image 170
vitas Avatar answered Nov 11 '22 18:11

vitas