Announcement (2017-05-07): www.ruby-forum.com is now read-only since I
unfortunately do not have the time to support and maintain the forum any
more. Please see rubyonrails.org/community and ruby-lang.org/en/community
for other Rails- und Ruby-related community platforms.

I am trying to figure out how to write a conditional statement that will
execute only if a specified variable is not empty.
Right now my view looks like this:
<dt>Building Regulations</dt>
<% for link in @cat1 %>
<dd><a href="<%= link.url %>"><%= link.title %></a></dd>
<% end %>
Action:
@cat1 = Link.find(:all, :conditions => "category = '1' ")
But I want it to be something like this:
<% if @cat1 != "" %>
<dt>Building Regulations</dt>
<% for link in @cat1 %>
<dd><a href="<%= link.url %>"><%= link.title %></a></dd>
<% end %>
<% end %>
the "<% if @cat1 != "" %>" is the part I cannot figure out how to say.
Thanks.

On May 2, 2006, at 01:35 PM, ben wrote:
> Action:> @cat1 = Link.find(:all, :conditions => "category = '1' ")
Key point, when you do a find :all, what you get back is an Array. So
what you need to test for is whether the array is empty.
>> the "<% if @cat1 != "" %>" is the part I cannot figure out how to say.
Change that line to: "<% unless @cat1.empty? %>". This way you are
telling Ruby to evaluate the block only when @cat1 has items to
process. Of course, you don't really need to do this in this way. I
would actually eliminate the unless block altogether. The "for link
in @cat1" loop statement will simply not fire if @cat1 is empty.
So that just leaves the Building Regulations line. I would probably
change that to:
<%= @cat1.empty? ? "" : "<dt>Building Regulations</dt>" %>
And if you're OK with that, the next step would be to replace the for
loop with:
<%= render :partial=>"link", :collection => @cat %>
That will really clean up your view code.
-Brian

On May 2, 2006, at 01:59 PM, Jean-François wrote:
> 2006/5/2, Lindsay B. <removed_email_address@domain.invalid>:>>> > the "<% if @cat1 != "" %>" is the part I cannot figure out how>> to say.>>>> How about:>>>> <% unless @cat1.size == 0 %>>> How about : <% unless @cat1.empty? -%> ?
In fact, I would say that you would always use this form, over
checking for a length of zero. Checking for Array length is something
you do when you need to do something numeric with that value. If you
want to know if an Array is empty, that's asking the object for a
boolean value, not a number...
-Brian