Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Ruby on Rails each loop, is there a good way to do something if nothing was iterated?

Is there an easy way to say: else, if there was nothing looped, show 'No objects.' Seems like there should be a nice syntactical way to do this rather than calculate the length of @user.find_object("param")

like image 763
Geoff Avatar asked Oct 13 '12 04:10

Geoff


People also ask

Do you know the best way to iterate through the items of an array?

The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.

How do you skip iterations in Ruby?

skip to the next iteration while part way through the current interation – this is done using the “next” keyword. exit the loop early – this is done using the “break” keyword. redo the current iteration – this is done using the “redo” keyword.

How do you stop an infinite loop in Ruby?

This means that the loop will run forever ( infinite loop ). To stop this, we can use break and we have used it. if a == "n" -> break : If a user enters n ( n for no ), then the loop will stop there. Any other statement of the loop will not be further executed.

What is the generally accepted method to loop over the elements in an array in Ruby?

To iterate over an array in Ruby, use the . each method. It is preferred over a for loop as it is guaranteed to iterate through each element of an array.


2 Answers

You can do something like:

if @collection.blank?
  # @collection was empty
else
  @collection.each do |object|
    # Your iteration  logic
  end
end
like image 104
Erez Rabih Avatar answered Sep 22 '22 02:09

Erez Rabih


Rails view

# index.html.erb
<h1>Products</h1>
<%= render(@products) || content_tag(:p, 'There are no products available.') %> 

# Equivalent to `render :partial => "product", @collection => @products

render(@products) will return nil when @products is empty.

Ruby

puts "no objects" if @collection.blank?

@collection.each do |item|
  # do something
end

# You *could* wrap this up in a method if you *really* wanted to:

def each_else(list, message)
  puts message if list.empty?

  list.each { |i| yield i }
end

a = [1, 2, 3]

each_else(a, "no objects") do |item|
  puts item
end

1
2
3
=> [1, 2, 3]

each_else([], "no objects") do |item|
  puts item
end

no objects
=> []
like image 20
Erik Peterson Avatar answered Sep 21 '22 02:09

Erik Peterson