0

I need to shift an element to last position by condition. For ex. [1,2,3] and to put 1 in last in array, without executing unnecessary loops.

o/p [2,3,1] for the above condition array will be dynamic and put particular element on last by condition.

I tried like this:

sd = [1,2,3]
sd.map{|d| sd.last(d) if d ==1 }

but the output is [[3], nil, nil]

1 Answer 1

3

We have Array#rotate method :-

[3] pry(main)> a = [1,2,3]
=> [1, 2, 3]
[4] pry(main)> a.rotate(1)
=> [2, 3, 1]
[5] pry(main)> a.rotate(2)
=> [3, 1, 2]

In your case, you should pass 1 as argument to the method #rotate. But 1 is default argument to the #rotate method, so you can omit it too. bang version of #rotate also exist.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.