Ruby: List Basics

By Xah Lee. Date: . Last updated: .

Creating List

# -*- coding: utf-8 -*-
# ruby

a = [0, 1, 2, "more", 4, 5, 6]
p a

Number of Elements

# -*- coding: utf-8 -*-
# ruby

a = ["more", 4, 6]
p a.length # 3

Get a Element

List element can be extracted by appending a square bracket with index.

# -*- coding: utf-8 -*-
# ruby

a = ["more", 4, 6]
p a[1] # 4

Negative index counts from right.

# -*- coding: utf-8 -*-
# ruby

a = ["more", 4, 6]
p a[-1] # 6

Get Sublist

Consecutive elements can be extracted using the form myList[startIndex,count].

# -*- coding: utf-8 -*-
# ruby

a = ["zero", "one", "two", "three", "four", "five"]
p a[0,2] # ["zero", "one"]

# first is index, second is count.

Change Element

A element can be changed with the form mylist[index] = new_value.

# -*- coding: utf-8 -*-
# ruby

a = [0, 1, 2]
a[2] = "two"
p a # [0, 1, "two"]

A slice (continuous sequence) of elements can be changed by assigning to a list directly. The length of the slice need not match the length of new list.

# -*- coding: utf-8 -*-
# ruby

a = ["zero","one","two","three","four","five","six"]

# change 4 elements of list to a new list, starting at index 2
a[2,4] = ["x", "y"]
p a # ["zero", "one", "x", "y", "six"]

Nested List

List can be nested arbitrarily. Append extra bracket to get element of nested list.

# -*- coding: utf-8 -*-
# ruby

a = [3, 4, [7, 8]]
p a[2][1] # returns 8

Join 2 Lists

List can be joined with plus sign.

# -*- coding: utf-8 -*-
# ruby

b = ["a", "b"] + [7, 6]
p b # ["a", "b", 7, 6]

If you have a question, put $5 at patreon and message me.

  1. Ruby Basics
  2. Doc Lookup
  3. Print Version String
  4. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?

  1. Unicode 💎
  2. Quote String
  3. Quote Long String
  4. Format String
  5. String Operations
  6. True, False
  7. “if then else”
  8. for, while, Loop
  9. List
  10. Loop Thru List
  11. Hash Table
  12. Function Optional Parameter
  13. Map f to List
  14. Complex Numbers
  1. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  2. Predefined Global Variables