for .. in .. else?

  • Thread starter Douglas Livingstone
  • Start date
D

Douglas Livingstone

In my erb templates, I've got this pattern quite often:

<table>
<th>Songs</th>
<% for aSong in songList %>
<td><%= aSong.name %></td>
<% end %>
<% unless songList.empty? %>
<td>no songs!</td>
<% end %>
</table>

Is there any way to write is more like this:

<table>
<th>Songs</th>
<% for aSong in songList %>
<td><%= aSong.name %></td>
<% else %>
<td>no songs!</td>
<% end %>
</table>

Thanks,
Douglas
 
D

David A. Black

Hi --

In my erb templates, I've got this pattern quite often:

<table>
<th>Songs</th>
<% for aSong in songList %>
<td><%= aSong.name %></td>
<% end %>
<% unless songList.empty? %>
<td>no songs!</td>
<% end %>
</table>

Is there any way to write is more like this:

<table>
<th>Songs</th>
<% for aSong in songList %>
<td><%= aSong.name %></td>
<% else %>
<td>no songs!</td>
<% end %>
</table>

How about (untested):

<table>
<tr>
<th>Songs</th>
</tr>
<% if song_list.empty? %>
<tr>
<td>no songs!</td>
</tr>
<% else %>
<% for song in song_list %>
<tr>
<td><%= song.name %></td>
</tr>
<% end %>
<% end %>
</tr>
</table>

(caMelCaSe method and variable name cleansing at no extra charge :)


David
 
L

Lionel Thiry

Douglas Livingstone a écrit :
In my erb templates, I've got this pattern quite often:

<table>
<th>Songs</th>
<% for aSong in songList %>
<td><%= aSong.name %></td>
<% end %>
<% unless songList.empty? %>
<td>no songs!</td>
<% end %>
</table>

Is there any way to write is more like this:

<table>
<th>Songs</th>
<% for aSong in songList %>
<td><%= aSong.name %></td>
<% else %>
<td>no songs!</td>
<% end %>
</table>

<table>
<th>Songs</th>
<% (songList.empty? ? ["no songs!"] : songList).each do |aSong| %>
<td><%= aSong %></td>
<% end %>
</table>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,170
Messages
2,570,925
Members
47,468
Latest member
Fannie44U3

Latest Threads

Top