necker
necker

Reputation: 7143

How to move first element to the end of array

What is the best way to move the first element of the array till the end of this same array?

ie: [a,b,c,d]

"Some operation"

result: [b,c,d,a]

What should this "Some operation" be?

Upvotes: 22

Views: 12859

Answers (4)

Vikram Jain
Vikram Jain

Reputation: 5588

    result=[a,b,c,d]
#first add first char at last in array
    result << result[0]
#remove first character from array
    result.shift 

Upvotes: 1

the Tin Man
the Tin Man

Reputation: 160551

As @sawa says, use rotate. In other/older languages we'd do something like:

ary.push(ary.shift)

or wire up something by splitting/slicing the array in multiple steps.

The above is useful for a left-shift of the array. Reversing the direction is:

ary.unshift(ary.pop)

which is occasionally useful, along with the above, for simulating bit-twiddling at the binary level.

Upvotes: 3

Arup Rakshit
Arup Rakshit

Reputation: 118261

Yes possible using Array#shift

a = [1,2,7,4]
a << a.shift
a # => [2, 7, 4, 1]

Upvotes: 5

sawa
sawa

Reputation: 168081

There is Array#rotate:

[a,b,c,d].rotate(1)

Upvotes: 54

Related Questions