You don't need to repeat "a"
. Put them in one:
arr.insert(2, arr.delete("a"))
Question
Say I have...
arr = ["a", "b", "c"]
...and I want to move "a" between "b" and "c". I currently do
arr.delete("a")
arr.insert(2, "a")
Can I do that in a single operation?
Thanks
Solution 2
You don't need to repeat "a"
. Put them in one:
arr.insert(2, arr.delete("a"))
OTHER TIPS
You can use parallel assignment:
arr[0], arr[1] = arr[1], arr[0]
=> ["b", "a"]
arr
=> ["b", "a", "c"]
If you want to move "a" between "b" and "c", then you should do:
arr.insert(1, arr.delete_at(0))
※Use .delete_at
instead of .delete
because you may have multiple 'a'
in your array.
Insert a after b, regardless of where they are in the array:
arr.insert(arr.index("b"), arr.delete_at(arr.index("a")))
=> ["b", "a", "c"]
You could also do:
arr[arr.index("a")], arr[arr.index("b")] = "b","a"
Use Array#shuffle!
arr = [ "a","b","c" ]
arr.shuffle! until arr[1] == 'a' && arr[0]=='b'
p arr #=> ["b", "a", "c"]