Skip to content

@nhocki /ruby_array.rb
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.