-5

When running trough a collection in the view you can do:

    <% @foo.each do |bar|
    #Do stuff
    <% end.empty? %>
    #if empty stuff
    <% end %>

This is really really nice for the view, but i cant seem to find a way for rake tasks, or other ruby related code.

Is there a nice ruby way of doing this?

EDIT: Solution by @meagar http://rubyfiddle.com/riddles/6d37b/2 Forgot the if

     if foo.each do |bar|
       puts "Bar #{bar}"
     end.empty?
       puts "Foo is empty"
     end
Community
  • 1
  • 1
xhoy
  • 34
  • 3
  • What does that even mean, you "can't find a way for rake tasks or other ruby code"? The code you've written works fine, in our out of ERB. You just need to drop the `<% %>`. That said, why would you want to do this in a rake task? Just use `if @foo.empty? ... else ...` – user229044 Jun 06 '14 at 19:19
  • This code doesn't work out side of ERB. since end.empty? it's some kind of helper – xhoy Jun 06 '14 at 19:22
  • 1
    What you've posted doesn't work inside *or* outside of ERB because you're missing an opening `if`. If you'd written it correctly (as written in the answer you linked) it would work just fine outside of ERB. See this if you don't believe me: http://rubyfiddle.com/riddles/6d37b/2 – user229044 Jun 06 '14 at 19:27
  • `end.empty?` is part of Ruby. It's not a helper, it has nothing to do with ERB. It will work everywhere. – user229044 Jun 06 '14 at 19:31
  • if i didn't mis that if! – xhoy Jun 06 '14 at 19:32

1 Answers1

4

The cleanest solution is probably the simplest.

if @foo.empty?
  #Do empty stuff
else
  @foo.each do |item|
    #Do non-empty stuff
  end
end
MCBama
  • 1,432
  • 10
  • 18