Add new value to top of an Array

S

Sam T.

Hi, Does anyone know how to add a new value to the top of an array,
instead of the bottom. eg. When using <<, this appends to the end.
 
J

J-H Johansen

[Note: parts of this message were removed to make it a legal post.]

Hi, Does anyone know how to add a new value to the top of an array,
instead of the bottom. eg. When using <<, this appends to the end.
a = [ "b", "c", "d" ]

a.unshift("a") => ["a", "b", "c", "d"]
 
I

Ian M. Asaff

[Note: parts of this message were removed to make it a legal post.]

ruby-1.9.2-p136 :009 > x = [2,3,4]
=> [2, 3, 4]
ruby-1.9.2-p136 :010 > x.unshift(5)
=> [5, 2, 3, 4]
 
A

Anurag Priyam

Hi, Does anyone know how to add a new value to the top of an array,
instead of the bottom. eg. When using <<, this appends to the end.

Array#unshift
 
B

botp

SOLVED: Cheers...

note, there is also Array#insert.
i usually use it since

a. i can insert *anywhere on the array w autofill features,
b. a similar method of the same name also works on Strings
c. i just need to remember one command ;-)

btw, others may not think that "top" of array is first element ;-)

best regards -botp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,813
Members
47,357
Latest member
sitele8746

Latest Threads

Top