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")
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.
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.
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.
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.
You can do something like:
if @collection.blank?
# @collection was empty
else
@collection.each do |object|
# Your iteration logic
end
end
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
=> []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With