Over a million developers have joined DZone.
Silver Partner

Swap Elements Of An Array In Ruby

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with JetBrains. Produce high quality code with no additional effort, thanks to state-of-the-art code analysis, on-the-fly error prevention with PhpStorm.

class 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.

The Web Dev Zone is brought to you in partnership with JetBrains. Streamline your workflow by integrating with everything you need for productive development with WebStorm.

Topics:
ruby

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}