Oh yes, Ruby makes that nice and easy.
You don't have to create an Array using the brackets notation - they're objects, just like everything else, so have a 'new' method, and it's surprisingly flexible...
Code: Select all
# A new, empty Array.
my_array = Array.new
# A new Array of the given size, with all elements set to nil.
my_array = Array.new(size)
# A new Array of the given size, with all elements set to 'value'.
my_array = Array.new(size, value)
# A new Array of the given size, with each element calculated separately in a code block.
my_array = Array.new(size) do |index|
# Compute a value for the element, using the element's 'index' if necessary.
end
### OR ###
my_array = Array.new(size){|index| #Calculate }
There's one little caveat that you have to watch out for, depending what you want inside the Array. The "Array.new(size, value)" form doesn't make a new copy of the value for each element, they're all references to the original object. That's no problem for simple, numeric elements, but can catch you out if you're using, say, Strings or nested sub-Arrays...
Code: Select all
# All elements point to the same String...
my_array = Array.new(10, "hello")
my_array[3].upcase! # Alters the String "in-place" without creating a new one.
my_array[3] #=> "HELLO"
my_array[9] #=> "HELLO" -- oops, probably not what we wanted!
# Unique, but identical elements...
my_array = Array.new(10){|index| "hello" }
my_array[3].upcase!
my_array[3] #=> "HELLO"
my_array[9] #=> "hello" -- that's better!
@tulamide - you beat me to it!

But I thought the "same object" thing was worth going into further, as it's such a common "gotcha" for new Rubyists when using container classes.