Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby equivalent for Python's for / else

Tags:

ruby

I've always been searching for something like Python's while / else struct in Ruby to improve my code.

That means that the loop is executed and if the condition in the loop hasn't been true any time, then it returns the value in the else statement.

In ruby, I can do like this :

if @items.empty?
  "Empty"
else
  @items.each do |item|
    item
  end
end

So is there a way to improve this ?

Thank you in advance.

like image 498
Cydonia7 Avatar asked Aug 17 '11 09:08

Cydonia7


1 Answers

Remember that the iterator block returns what you put into it, which can be tested for further use.

if arr.each do |item|
  item.some_action(some_arg)
end.empty?
  else_condition_here
end
like image 101
scootklein Avatar answered Oct 16 '22 18:10

scootklein