2012-04-23 152 views
1

當然枚舉的Ruby中並不存在,但基於this post我用類似如下:紅寶石「枚舉」比較

class PostType 
    Page = 1, 
    Post = 2 
end 

我想要的價值傳遞給方法,並用它作比較。所以:

initialize(post_type) 
    if post_type = PostType::Page 
     # do something here 
    elsif post_type = PostType::Post 
     # do something else here 
    end 
end 

但是這不起作用,無論我傳入我的類的構造函數,它總是產生相同的結果。

有關爲什麼將「假枚舉」傳遞給方法並試圖比較它的任何想法都行不通?我需要比較價值嗎?即post_type = 2

回答

4

分配,而不是比較

initialize(post_type) 
    if post_type == PostType::Page 
     # do something here 
    elsif post_type == PostType::Post 
     # do something else here 
    end 
end 
+0

當,有我認爲比較的Ruby語法是single ='s。愚蠢的錯誤。乾杯! – Kezzer 2012-04-23 13:27:07

+1

如果使用「ruby -w」,則會在條件表達式中使用賦值的警告。比我想象的更好? – Romain 2012-04-23 13:30:58

+0

你是對的,但我不是我們的-w本人很大程度上導致我的結果,真正的錯誤往往會被他們混淆,往往它是關於在你不控制的寶石中棄用的東西的評論 – peter 2012-04-23 13:38:56

4

除此之外,您還應該使用Symbol S中的事實,有一個語法錯誤,我想你想不同的語義:

if post_type = PostType::Page 

應該

if post_type == PostType::Page 

所以你的代碼應該看起來像

if post_type == :page 
... 
+1

他們爲什麼需要要符號?我不明白這一點...... – Romain 2012-04-23 13:23:22

+1

因爲這是紅寶石的方式。如果你使用ruby代碼,使用ruby的思維模式,而不是使用魔法數字的思維模式。 – Reactormonk 2012-04-23 13:26:49

+0

好的,但雖然它是正確的,但我認爲它與原始問題不無關係。但最終I + 1基於事實,你的觀點歸結爲「你不能在Java中使用Java中的枚舉類型(例如)獲得類型安全性。」 – Romain 2012-04-23 13:30:17

4

您正在分配而不是比較。使用==而不是=應該會產生更好的結果。

initialize(post_type) 
    if post_type == PostType::Page 
     # do something here 
    elsif post_type == PostType::Post 
     # do something else here 
    end 
end 
1

這就是爲什麼這樣做一個好習慣:

def initialize(post_type) 
    if PostType::Page == post_type 
     # do something here 
    elsif PostType::Post == post_type 
     # do something else here 
    end 
end 

如果你犯這樣的錯誤,編譯器會做出警告"already initialized constant ..."

3

你可以使用一個case

case post_type 
    when PostType::Page then # Do something 
    when PostType::Post then # Do something else 
    else raise 'Invalid post type' 
end 

此外,你真的應該使用Symbol s爲t他:

case post_type 
    when :page then # Do something 
    when :post then # Do something else 
    else raise 'Invalid post type' 
end