方法,我有一個返回哈希,或無的方法:使用紅寶石「或者等於」 || =上返回散列或無
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
顯然我的例子運行有點瘦,還有其他解決這個問題的方法,但如果|| =可以使用,我很想知道如何。
謝謝!
我喜歡你的答案。爲什麼它感覺不太對? – klew 2010-02-13 14:11:25
或'(self.person_of_my_age(age)|| {})['height'] || 0'或'(self.person_of_mY_age(age)|| {})。fetch('height',0)' – 2010-02-13 14:29:39