Last active
December 14, 2015 00:49
-
-
Save nhocki/5002120 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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