Olivia
Olivia

Reputation: 195

Re-order ruby array

I have a ruby array:

["A", "C", "B", "D", "F", "E"]

User will supply an input, e.g.

input = "B"

I want to shift the values in the array, so the first item of the array equals input, and get the result of a new array:

["B", "D", "F", "E", "A", "C"]

User will be choosing from a dropdown options, so they can only choose the letters from original array.

Upvotes: 1

Views: 111

Answers (1)

Sagar Pandya
Sagar Pandya

Reputation: 9508

You can use Array#rotate.

arr = ["A", "C", "B", "D", "F", "E"]

arr.rotate(arr.index('B'))
 #=> ["B", "D", "F", "E", "A", "C"]

Upvotes: 5

Related Questions