Ruby/Array/Array.new

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Array initialized by copying

squares = Array.new(5) {|i| i*i}
copy = Array.new(squares) # initialized by copying
p squares[5] = 25



Array.new(2) creates an array with two nil values

p Array.new(2)



Array.new(5, "A") fills an array with five a

p Array.new(5, "A")



Array.new creates an empty array

p Array.new



Array with Array.new

empty = Array.new       # []: returns a new empty array
nils = Array.new(3)     # [nil, nil, nil]: new array with 3 nil elements
zeros = Array.new(4, 0) # [0, 0, 0, 0]: new array with 4 0 elements
copy = Array.new(nils)  # Make a new copy of an existing array
count = Array.new(3) {|i| i+1}  # [1,2,3]: 3 elements computed from index



Create an array of hashes

a = Array.new(2, Hash.new)
a[0]["cat"] = "feline"
p a  
a[1]["cat"] = "Felix"
p a



Fill an array of hashes

a = Array.new(2) { Hash.new } # Multiple instances
p a[0]["cat"] = "feline"