7

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")

Erik Peterson
  • 4,281
  • 1
  • 22
  • 32
Geoff
  • 9,470
  • 13
  • 52
  • 67

4 Answers4

7

You can do something like:

if @collection.blank?
  # @collection was empty
else
  @collection.each do |object|
    # Your iteration  logic
  end
end
Erez Rabih
  • 15,562
  • 3
  • 47
  • 64
  • 3
    this is the normal although verbose way to do it. Note that `blank?` can shadow some problems (the value should not be `nil`), `empty?` is more specific. – tokland Oct 13 '12 at 09:00
5

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
=> []
Erik Peterson
  • 4,281
  • 1
  • 22
  • 32
0
if @array.present?
  @array.each do |content|
    #logic
  end
else
  #your message here
end
Manjunath Manoharan
  • 4,567
  • 6
  • 28
  • 43
0

I do the following:

<% unless @collection.empty? %>
<% @collection.each do |object| %>
    # Your iteration  logic
  <% end %>
<% end %>
gavit
  • 509
  • 3
  • 6