DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Reversing an Array: An Exploration of Array Manipulation
  • Unlocking the Potential of Binary Search Trees with C# Programming
  • Sliding Window
  • Binary Search in Python

Trending

  • Production Checklist for Tool-Using AI Agents in Enterprise Apps
  • RAG Done Right: When to Use SQL, Search, and Vector Retrieval and How To Combine Them
  • Building a Production-Ready AI Agent in 2026: Beyond the Hello World Demo
  • AI Paradigm Shift: Analytics Without SQL
  1. DZone
  2. Data Engineering
  3. Data
  4. Swap Elements Of An Array In Ruby

Swap Elements Of An Array In Ruby

By 
Snippets Manager user avatar
Snippets Manager
·
May. 13, 05 · Code Snippet
Likes (0)
Comment
Save
Tweet
Share
12.7K Views

Join the DZone community and get the full member experience.

Join For Free
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.
Data structure Element

Opinions expressed by DZone contributors are their own.

Related

  • Reversing an Array: An Exploration of Array Manipulation
  • Unlocking the Potential of Binary Search Trees with C# Programming
  • Sliding Window
  • Binary Search in Python

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook