0
0
RubyHow-ToBeginner · 3 min read

How to Create Array in Ruby: Syntax and Examples

In Ruby, you create an array using square brackets [] with elements separated by commas, like array = [1, 2, 3]. Arrays can hold any type of data, including numbers, strings, or mixed types.
📐

Syntax

To create an array in Ruby, use square brackets [] and separate elements with commas. You can include any type of data inside the array.

  • Square brackets: Define the array.
  • Elements: Values inside the array, separated by commas.
ruby
array = [1, 2, 3, 4]
empty_array = []
mixed_array = [1, "hello", 3.14, true]
💻

Example

This example shows how to create arrays with numbers, strings, and mixed data types, then prints them.

ruby
numbers = [10, 20, 30]
words = ["apple", "banana", "cherry"]
mixed = [1, "two", 3.0, false]

puts "Numbers: #{numbers}"
puts "Words: #{words}"
puts "Mixed: #{mixed}"
Output
Numbers: [10, 20, 30] Words: ["apple", "banana", "cherry"] Mixed: [1, "two", 3.0, false]
⚠️

Common Pitfalls

Common mistakes include forgetting commas between elements or using parentheses instead of square brackets.

Wrong: array = (1 2 3) (missing commas and wrong brackets)

Right: array = [1, 2, 3]

ruby
wrong_array = (1, 2, 3) # SyntaxError
correct_array = [1, 2, 3]
📊

Quick Reference

ActionSyntax Example
Create empty arrayempty = []
Create array with numbersnums = [1, 2, 3]
Create array with stringswords = ["a", "b", "c"]
Create mixed arraymixed = [1, "two", 3.0, true]

Key Takeaways

Use square brackets [] with commas to create arrays in Ruby.
Arrays can hold any type of data, including mixed types.
Always separate elements with commas to avoid syntax errors.
Empty arrays are created with empty square brackets [].
Parentheses () cannot be used to create arrays.