Array Creation
In this page:
Array Creation
A Ruby array is created with square brackets, [1, 2, 3], or with Array.new, and can hold elements of mixed types since Ruby is dynamically typed. Arrays are ordered and zero-indexed. Array.new(n) { |i| ... } builds an array by calling a block for each index, useful for generating data programmatically.
Note: Array.new(5) { |i| i * i } builds [0, 1, 4, 9, 16] in one line without a separate loop.
Example: Array Creation
fruits = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, true]
squares = Array.new(5) { |i| i * i }
puts fruits.inspect
puts mixed.inspect
puts squares.inspect
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: