Ruby: List Basics

, ,

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]
blog comments powered by Disqus