Skip to content

Instantly share code, notes, and snippets.

@nhocki
Last active December 14, 2015 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nhocki/5002120 to your computer and use it in GitHub Desktop.
Save nhocki/5002120 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment