Let's say I have a class Counter in ruby, defined as
class Counter
attr_accessor :starting_value
def initialize(starting_value)
@starting_value = starting_value
end
def tick
@starting_value = @starting_value + 1
end
end
and I want to fill an array with that object, using a default parameter, like this:
counter_arr = Array.new(5, Counter.new(0))
This is almost what I want, except that I now have an array that contains the same instance of a counter 5 times, instead of an array of 5 new counters. IE when I run the code
counter_arr = Array.new(5, Counter.new(0))
counter_arr[0].tick
counter_arr.each do |c|
puts(c.starting_value)
end
I output
1
1
1
1
1
instead of
1
0
0
0
0
I was wondering, what is the "ruby-esque" way to initialize an array with multiple new instances of an object?
@starting_value += 1. That's usually less verbose and avoids typographical errors.Array::newwhich answer this very question.