Is there an easier way?
class Store
def check_inventory
@inventory ||= []
@inventory.each { ... }
end
end
Can the lines with the instance variables开发者_开发知识库 on them be turned into a one-liner?
Yes!! There is always a cool hack in Ruby!
class Store
def check_inventory
@inventory.to_a.each { ... }
end
end
The reason this works is Cool Ruby Feature number 9,123: as it happens, NilClass
implements a #to_a
method that returns []
! How awesome is that?!
edtq ross$ irb --prompt-mode simple
>> nil.to_a
=> []
>> @this_does_not_exist.to_a
=> []
DigitalRoss's answer is almost the same, but it will never change @inventory
; your code will ensure that @inventory
is always an array. If you need that behavior, you can just straightforwardly combine the two lines:
class Store
def check_inventory
(@inventory ||= []).each { ... }
end
end
精彩评论