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. Unicode 💎
  5. Quote String
  6. Quote Long String
  7. Format String
  8. String Operations
  9. True, False
  10. “if then else”
  11. for, while, Loop
  12. List
  13. Loop Thru List
  14. Hash Table
  15. Function Optional Parameter
  16. Map f to List
  17. Complex Numbers
  18. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  19. Predefined Global Variables
  20. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?