Class Array Flashcards
Creating Arrays: literal constructor []
A new array can be created by using the literal constructor []. Arrays can contain different types of objects. For example, the array below contains an Integer, a String and a Float:
ary = [1, “two”, 3.0] #=> [1, “two”, 3.0]
Creating Arrays: explicitly calling ::new
An array can also be created by explicitly calling ::new with zero, one (the initial size of the Array) or two arguments (the initial size and a default object).
ary = Array.new #=> []
Array.new(3) #=> [nil, nil, nil]
Array.new(3, true) #=> [true, true, true]
Creating Arrays: To create an array with separate objects a block can be passed instead. This method is safe to use with mutable objects such as hashes, strings or other arrays:
Array.new(4) { Hash.new } #=> [{}, {}, {}, {}]
Creating Arrays: multi-dimensional arrays with block
empty_table = Array.new(3) { Array.new(3) } #=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
Creating Arrays: Array() method
An array can also be created by using the Array() method, provided by Kernel, which tries to call to_ary, then to_a on its argument.
Array({:a => “a”, :b => “b”}) #=> [[:a, “a”], [:b, “b”]]