Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 7 / 68

Working with Arrays

In this lesson you will learn the basics of arrays in Ruby so you can handle several pieces of data together. This is for anyone searching for "Ruby array how to use" or "Ruby each_with_index".

An array is like a shelf of numbered drawers. You create one with [ ] and take items out with their number using each_with_index. Arrays come with a great many useful methods.

The sample code builds a fruits array and uses each_with_index do |fruit, i| to take the value (fruit) and the index (i) at the same time. Notice how i + 1 turns it into numbering that starts at 1.

A common stumbling block for beginners is that array indexes start at 0. Since i starts at 0, displaying a human-friendly "first" requires the i + 1 adjustment. The << operator is also commonly used to append to an array, meaning the same as push.

You can express a great deal concisely without ever writing a for statement. In real Ruby code, iterating with each is the standard style.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)