I have a method that returns a hash, or nil:
我有一个返回哈希或nil的方法:
def person_of_age(age)
some_hash = @array_of_hashes.select { |h| h.age == age }.last
return some_hash
end
I want to use this hash like so:
我想用这样的哈希表:
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
Now, if the hash returns nil, ruby doesn't like me using ['height']:
现在,如果哈希返回nil, ruby不喜欢我使用['height']:
undefined method `[]' for nil:NilClass (NoMethodError)
Fair enough, but how can I use ||= to avoid this problem? If the method does return nil, let's just say I want the 'height' to be 0.
很好,但是我如何使用||=来避免这个问题?如果这个方法返回nil,我们就说我想要“高度”为0。
I have tried things along the lines of, to no avail:
我已经尝试过了,但没有成功:
if my_height < self.person_of_age(age)||={ 'height' => 0 }['height']
#...
if my_height < self.person_of_age(age)['height'] ||= 0
Clearly my example is running a little thin, and there are other ways around this problem, but if ||= can be used I'd love to know how.
显然,我的例子有点牵强,有其他方法可以解决这个问题,但是如果||=可以使用,我很想知道如何使用。
Thank you!
谢谢你!
3 个解决方案
#1
4
obvious:
显而易见的:
(self.person_of_my_age(age) || {'height' => 0})['height']
but somehow this does not feel so right
但不知何故,这感觉不太对
#2
2
You can do it like this:
你可以这样做:
if my_height < self.person_of_age(age).nil? ? 0 : self.person_of_age(age)['height']
Or you can rewrite person_of_age
method:
或者可以重写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
or simpler
或者更简单的
def person_of_age(age)
@array_of_hashes.select { |h| h.age == age }.last || {:height => 0}
end
#3
1
I'm not sure if this helps in your circumstance, but one capability Hash has is
我不确定这是否对您的情况有所帮助,但是一个功能散列是。
hash.fetch(key) { block_for_code_evaluated_if_key_absent }
#1
4
obvious:
显而易见的:
(self.person_of_my_age(age) || {'height' => 0})['height']
but somehow this does not feel so right
但不知何故,这感觉不太对
#2
2
You can do it like this:
你可以这样做:
if my_height < self.person_of_age(age).nil? ? 0 : self.person_of_age(age)['height']
Or you can rewrite person_of_age
method:
或者可以重写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
or simpler
或者更简单的
def person_of_age(age)
@array_of_hashes.select { |h| h.age == age }.last || {:height => 0}
end
#3
1
I'm not sure if this helps in your circumstance, but one capability Hash has is
我不确定这是否对您的情况有所帮助,但是一个功能散列是。
hash.fetch(key) { block_for_code_evaluated_if_key_absent }