Swap Elements Of An Array In Ruby
Join the DZone community and get the full member experience.
Join For Freeclass Array
def swap!(a,b)
self[a], self[b] = self[b], self[a]
self
end
end
โ
You can now do stuff like..
โ
[1,2,3,4].swap!(2,3) # = [1,2,4,3] etc..
โ
Many thanks to Sam Stephenson and technoweenie for their suggestions.
Opinions expressed by DZone contributors are their own.
Comments