Ruby Tuesday – Array#push

Today’s Ruby Tuesday is on Array#push.

Array#push takes a item and appends that item to an existing Array.

[].push 1
# => [1]
[3, 7, 5].push 1
# => [3, 7, 5, 1]
[3, 7, 5].push []
# => [3, 7, 5, []]
[3, 7, 5].push nil
# => [3, 7, 5, nil]

Array#push also returns itself as the return value, allowing you to chain together calls.

[3, 7, 5].push(2).push(8).push(6)
# => [3, 7, 5, 2, 8, 6]
q = [3, 7, 5]
# => [3, 7, 5]
q.push(2).push(8).push(6)
# => [3, 7, 5, 2, 8, 6]
q
# => [3, 7, 5, 2, 8, 6]

You can also pass more than one argument to Array#push, and it will push each of those items to the Array in turn.

[3, 7, 5].push(2, 8, 6)
# => [3, 7, 5, 2, 8, 6]
[3, 7, 5].push(*[2, 8, 6])
# => [3, 7, 5, 2, 8, 6]

–Proctor

One thought on “Ruby Tuesday – Array#push

  1. Pingback: Ruby Tuesday – Array#popProctor It | Proctor It

Leave a Reply

Your email address will not be published. Required fields are marked *