Reputation: 7143
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
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
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
Reputation: 118261
Yes possible using Array#shift
a = [1,2,7,4]
a << a.shift
a # => [2, 7, 4, 1]
Upvotes: 5