19858

How do I swap array elements using parallel assignment?

Question:

I am trying to swap two elements in an array like this

deck = [] (deck << (1..52).to_a << 'A' << 'B').flatten! p deck deck[deck.index("A")], deck[deck.index("B")] = deck[deck.index("B")], deck[deck.index("A")] #swap "A" and "B" p deck

But it doesnt swap. If i do this, however:

deck[52], deck[53] = deck[53], deck[52]

it works. Any suggestions?

Answer1:

To make things simple, let deck be just ['A', 'B']. Here is step-by-step evaluation:

deck = ['A', 'B'] deck[deck.index("A")], deck[deck.index("B")] = deck[deck.index("B")], deck[deck.index("A")] # deck == ['A', 'B'] deck[deck.index("A")], deck[deck.index("B")] = deck[1], deck[0] # deck == ['A', 'B'] deck[deck.index("A")], deck[deck.index("B")] = 'B', 'A' # deck == ['A', 'B'] deck[0], deck[deck.index("B")] = 'B', 'A' # deck == ['A', 'B'] # Applying first assignment. ..., deck[deck.index("B")] = ..., 'A' # deck == ['B', 'B'] # NOTE: deck.index("B") is 0 now, not 1! ..., deck[0] = ..., 'A' # deck == ['B', 'B'] # Applying second assignment. ... # deck == ['A', 'B']

So what your code actually does is just assinging twise to the same element of array.

In order to fix this issue, just save deck.index() values to temporary arrays:deck = [] (deck << (1..52).to_a << 'A' << 'B').flatten! p deck index_a, index_b = deck.index("A"), deck.index("B") deck[index_a], deck[index_b] = deck[index_b], deck[index_a] p deck

Recommend

  • in r combine a list of lists into one list
  • Push array into array on ruby by just one level
  • How to get the probabilities of classes in Spark Naive Bayes classifier?
  • turn two nested associative arrays into one flat array?
  • cd command not working with execvp
  • Problems with toDataURL HTML5 other ways to get canvas data?
  • Find JSON nested nodes using multiple string values
  • Sending keystrokes/mouse clicks to a Java program with Autohotkey
  • Debugging VB6 Code From Visual Studio 2010
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • Diff between two dataframes in pandas
  • Unable to install Git-core+svn by MacPorts
  • Appending Character to Character Array In C
  • Django simple Captcha “No module named fields” error
  • PHP CURL timing out but CLI CURL works
  • Declaring variable dynamically in VB.net
  • CakePHP 2.0.4 - findBy magic methods with conditions
  • Jackson Parser: ignore deserializing for type mismatch
  • How to match http request and response using Jersey ContainerRequestFilter and ContainerResponseFilt
  • MailKit: The IMAP server replied to the 'EXAMINE' command with a 'BAD' response
  • Could not find rake using whenever rails
  • Initializer list vs. initialization method
  • PHPUnit_Framework_TestCase class is not available. Fix… - Makegood , Eclipse
  • C# - Is there a limit to the size of an httpWebRequest stream?
  • Different response to non-authenticated users and AJAX calls
  • Date difference with leap year
  • How to recover from a Spring Social ExpiredAuthorizationException
  • How to add a column to a Pandas dataframe made of arrays of the n-preceding values of another column
  • ILMerge & Keep Assembly Name
  • Knitr HTML Loop - Some HTML output, some R output
  • Large data - storage and query
  • Rearranging Cells in UITableView Bug & Saving Changes
  • WOWZA + RTMP + HTML5 Playback?
  • Proper way to use connect-multiparty with express.js?
  • Benchmarking RAM performance - UWP and C#
  • Angular 2 constructor injection vs direct access
  • Can Visual Studio XAML designer handle font family names with spaces as a resource?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Conditional In-Line CSS for IE and Others?
  • How to load view controller without button in storyboard?