I have a struct like this:
class Item < Struct.new(:url, :list)
def list
@list ||= Array.new
end
end
I found out today that the .list() and [:list] returns different things:
i = Item.new
#=> #<struct Item url=nil, list=nil>
i.list
#=> []
i[:list]
#=> nil
i.list << 1
#=> [1]
i.list += [2]
#=> [1, 2]
i.list
#=> [1]
i[:list]
#=> [1, 2]
Why is this and how can I write my struct to have default empty array properly?
Assuming you want the other advantages of Struct and need to stick with it, you could write your own
initializemethod:Array()will ensure anything passed in will be put in an array if it’s not one already, and will return an empty array ([]) ifnilis the argument.