Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist
View ruby_array.rb
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
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.