Class Array Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Creating Arrays: literal constructor []

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Creating Arrays: explicitly calling ::new

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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:

A

Array.new(4) { Hash.new } #=> [{}, {}, {}, {}]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Creating Arrays: multi-dimensional arrays with block

A
empty_table = Array.new(3) { Array.new(3) }
#=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Creating Arrays: Array() method

A

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”]]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly