2010-02-13 72 views
2

方法,我有一個返回哈希,或無的方法:使用紅寶石「或者等於」 || =上返回散列或無

def person_of_age(age) 
    some_hash = @array_of_hashes.select { |h| h.age == age }.last 
    return some_hash 
end 

我想用這個哈希像這樣:

my_height = 170 
my_age = 30 
if my_height < self.person_of_age(my_age)['height'] 
puts "You are shorter than another person I know of the same age!" 
end 

現在,如果哈希返回nil,紅寶石不使用[「高度」]我一樣:

undefined method `[]' for nil:NilClass (NoMethodError) 

不夠公平,但我該如何使用|| =避免這個問題? 如果該方法返回nil,讓我們只說我想要的「高度」爲0

我已經試過的東西線沿線的,但無濟於事:

if my_height < self.person_of_age(age)||={ 'height' => 0 }['height'] 
#... 
if my_height < self.person_of_age(age)['height'] ||= 0 

顯然我的例子運行有點瘦,還有其他解決這個問題的方法,但如果|| =可以使用,我很想知道如何。

謝謝!

回答

4

明顯:

​​

但不知何故,這並不感覺很不錯

+0

我喜歡你的答案。爲什麼它感覺不太對? – klew 2010-02-13 14:11:25

+0

或'(self.person_of_my_age(age)|| {})['height'] || 0'或'(self.person_of_mY_age(age)|| {})。fetch('height',0)' – 2010-02-13 14:29:39

2

你可以這樣說:

if my_height < self.person_of_age(age).nil? ? 0 : self.person_of_age(age)['height'] 

或者你可以重寫person_of_age方法:

def person_of_age(age) 
    some_hash = @array_of_hashes.select { |h| h.age == age }.last || {:height => 0} 
    return some_hash 
end 

或簡單

def person_of_age(age) 
    @array_of_hashes.select { |h| h.age == age }.last || {:height => 0}  
end 
1

我不知道如果這有助於在你的情況,但有能力的Hash已經是

hash.fetch(key) { block_for_code_evaluated_if_key_absent }