2013-06-26 76 views
6

這是要聽起來不可思議,但我很樂意做這樣的事情:關於哈希的Ruby case語句?

case cool_hash 
    when cool_hash[:target] == "bullseye" then do_something_awesome 
    when cool_hash[:target] == "2 pointer" then do_something_less_awesome 
    when cool_hash[:crazy_option] == true then unleash_the_crazy_stuff 
    else raise "Hell" 
end 

理想情況下,我甚至不會需要引用又有因爲它是case語句是什麼。如果我只想使用一個選項,那麼我會「case cool_hash [:that_option]」,但我想使用任意數量的選項。另外,我知道Ruby中的case語句只評估第一個真正的條件塊,有沒有一種方法可以覆蓋這個來評估每個真正的塊,除非有一箇中斷?

回答

3

你的代碼是非常接近成爲有效的Ruby代碼。只需刪除第一行上的變量名稱,將其更改爲:

case 

但是,無法覆蓋case語句以評估多個塊。我認爲你想要的是使用if陳述。而不是break,則使用return跳出該方法。

def do_stuff(cool_hash) 
    did_stuff = false 

    if cool_hash[:target] == "bullseye" 
    do_something_awesome 
    did_stuff = true 
    end 

    if cool_hash[:target] == "2 pointer" 
    do_something_less_awesome 
    return # for example 
    end 

    if cool_hash[:crazy_option] == true 
    unleash_the_crazy_stuff 
    did_stuff = true 
    end 

    raise "hell" unless did_stuff 
end 
+0

非常感謝響應快!不勝感激。這有助於並希望隨着時間的推移,我會在Ruby中思考。 –

4

我認爲,下面是更好的方法來做你想要的東西。

def do_awesome_stuff(cool_hash) 
    case cool_hash[:target] 
    when "bullseye" 
     do_something_awesome 
    when "2 pointer" 
     do_something_less_awesome 
    else 
    if cool_hash[:crazy_option] 
     unleash_the_crazy_stuff 
    else 
     raise "Hell" 
    end 
    end 
end 

即使是在案件的其他部分,你可以使用「案例cool_hash [:crazy_option]」而不是「如果」,如果有更多的條件。在這種情況下,我更喜歡使用'if',因爲只有一個條件。

12

你也可以使用lambda:

case cool_hash 
when -> (h) { h[:key] == 'something' } 
    puts 'something' 
else 
    puts 'something else' 
end 
+0

正是我所期待的! – Yonk