Array Creation
An array is an ordered list of items kept together, like a row of lockers with numbers. You can create one with square brackets and fill it with anything.
In this page:
Syntax
array = [value1, value2, value3]
array = Array.new(size, default_value)
array = %w[word1 word2 word3]
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
Array.new(3, []), where all elements are the same array object; useArray.new(3) { [] }. - Using an index beyond the length such as
fruits[10], which returnsnilrather than an error. - Writing
%w[a b c]with commas, which puts the commas inside the strings.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: