Is there an easier way?

class Store
  def check_inventory
    @inventory ||= []
    @inventory.each { ... }
  end
end

Can strings with instance variables on them be turned into single-line?

+3
source share
2 answers

Yes!! Ruby always has a cool hack!


class Store
  def check_inventory
    @inventory.to_a.each { ... }
  end
end

The reason this works is Cool Ruby. Function number 9.123: as it happens, NilClassimplements a method #to_athat returns []! How amazing is that ?!

edtq ross$ irb --prompt-mode simple
>> nil.to_a
=> []
>> @this_does_not_exist.to_a
=> []
+12
source

DigitalRoss's answer is almost the same, but it will never change @inventory; your code ensures that @inventoryit is always an array. If you need this behavior, you can simply concatenate two lines:

class Store
  def check_inventory
    (@inventory ||= []).each { ... }
  end
end
+4
source

Source: https://habr.com/ru/post/1783065/


All Articles