๐ŸŽ“ A1Learner
๐Ÿ”

Ruby Array Methods

Array methods are built-in tools that work on a whole array. They can add items, read the ends, and build new values from the items.

Adding items with push

push adds eggs at the end of the list. The << sign then adds rice the same way.

list = ["milk", "bread"]
list.push("eggs")
list << "rice"
p list

The first and last items

first reads the item at the start of the list. last reads the item at the end.

list = ["milk", "bread", "eggs"]
puts list.first
puts list.last

Asking with include?

include? answers whether one item sits in the list. It answers true for bread and false for rice.

list = ["milk", "bread", "eggs"]
puts list.include?("bread")
puts list.include?("rice")

Ordering with sort

sort gives a new array with the numbers in order. The second p shows the first array in its old order.

numbers = [30, 10, 20]
p numbers.sort
p numbers

Building one string with join

join glues the words into one string with a comma and a space between them. p shows the string with its quotes.

words = ["red", "green", "blue"]
p words.join(", ")

Example

cart = ["pen", "book"]
cart.push("bag")
cart << "ruler"
puts cart.first
puts cart.include?("book")
p cart.sort
puts cart.join(" and ")

Key points

  • push adds an item at the end of an array.
  • The << sign also adds an item at the end of an array.
  • first reads the first item of an array.
  • last reads the last item of an array.
  • include? answers true or false for one item.
  • sort gives a new array with the items in order.
  • join glues the items of an array into one string.

In this example, the cart starts with a pen and a book. push adds a bag, and the << sign adds a ruler. The program then prints the first item, asks whether book is in the cart, prints a sorted copy, and joins the items into one line of text.

Note

sort leaves the first array in its old order.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Ruby Compiler

Exercise

What does p [3, 1, 2].sort print?