2

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

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
dublxdad
  • 153
  • 1
  • 12

5 Answers5

3

You can use parallel assignment:

arr[0], arr[1] = arr[1], arr[0]
=> ["b", "a"]
arr
=> ["b", "a", "c"]
2

You don't need to repeat "a". Put them in one:

arr.insert(2, arr.delete("a"))
sawa
  • 165,429
  • 45
  • 277
  • 381
2

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.

xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Use Array#shuffle!

arr = [ "a","b","c" ] 
arr.shuffle! until arr[1] == 'a' && arr[0]=='b'
p arr #=> ["b", "a", "c"]
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
0

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"
davogones
  • 7,321
  • 31
  • 36