2012-06-15 21 views
0

在我的ERB文件,我在body標籤下面的代碼:在Ruby中的「每個...做」的條件聲明?

<% @tasks.each do |task| %> 
    <%= task.name %> 
<% end %> 

這是工作,但我只想要顯示task.name如果task.otherAttribute不等於-1。

由於某種原因,我無法弄清楚如何做到這一點!任何提示很多將不勝感激。

預先感謝您。

回答

3

試試這個:

<% @tasks.each do |task| %> 
    <%= task.name if task.otherAttribute != 1 %> 
<% end %> 

或者:

<% @tasks.each do |task| %> 
    <%= task.name unless task.otherAttribute == 1 %> 
<% end %> 

我將提供一些更多的選擇以供將來參考:

<% @tasks.each do |task| %> 
    <% if task.otherAttribute != 1 %> 
    <%= task.name %> 
    <% end %> 
<% end %> 

<% @tasks.each do |task| %> 
    <%= task.otherAttribute == 1 ? '' : task.name %> 
<% end %> 

祝你好運!

+0

非常感謝,這樣做很有意義。 – tonic

0

您可以將條件語句放入您的ERB代碼中。

<%= task.name if task.otherAttribute != 1 %> 

您還可以使用更詳細的語法執行更復雜的任務。這不是你的情況有必要,但你也可以做更多傳統的if/else塊,像這樣:

<% if task.otherAttribute != 1 %> 
    <%= task.name %> 
<% end %> 
3

我傾向於使用#select#reject這個成語,因爲這是你做的基本上是什麼。

<%= @tasks.reject{|t| t.other_attribute == -1}.each do |task| %> 
    <%= task.name %> 
<% end %> 

這些來自Enumerable模塊,其中大部分的東西與#each方法包括。

+0

這是非常有用的,並按我的需要工作!但是,爲什麼你用「t」代替「任務」呢?不清楚那一點。 – tonic

+0

@tonic,'任務'也能正常工作。對我來說,使用1個字母的變量名實際上是不好的做法,儘管當塊只接受一個參數並且有一行邏輯時,我傾向於這樣做。用你的直覺去使用'task';) – d11wtq