public
Last active

  • Download Gist
ruby_array.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
require 'ostruct'
class House
attr_accessor :doors
def initialize(n = 3)
@doors = Array.new(n, OpenStruct.new(color: 'dummy', name: 'dummy'))
end
end
 
# won't work because ruby will *not* clone the object but use the same one
# 3 times.
h = House.new
puts h.doors[0].object_id # => 70357021610520
puts h.doors[1].object_id # => 70357021610520
 
# You need to manually create each one of them
 
class AnotherHouse
attr_accessor :doors
def initialize(n = 3)
@doors = n.times.map{|door| OpenStruct.new(color: 'dummy', name: 'dummy')}
end
end
 
h2 = AnotherHouse.new
puts h2.doors[0].object_id # => 70275299473840
puts h2.doors[1].object_id # => 70275299473200

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.