several ways to swap elements in [1, 2]? in ruby

There are several ways to swap elements in an array in Ruby. Here are four different approaches:

  1. Using a temporary variable:
main.rb
array = [1, 2]
temp = array[0]
array[0] = array[1]
array[1] = temp
puts array.inspect  # Output: [2, 1]
104 chars
6 lines
  1. Using parallel assignment:
main.rb
array = [1, 2]
array[0], array[1] = array[1], array[0]
puts array.inspect  # Output: [2, 1]
92 chars
4 lines
  1. Using the swap method from the Array class:
main.rb
array = [1, 2]
array.swap(0, 1)
puts array.inspect  # Output: [2, 1]
69 chars
4 lines

(Note: The swap method is not a built-in method in Ruby. You would need to define it yourself.)

  1. Using the reverse! method:
main.rb
array = [1, 2]
array.reverse!
puts array.inspect  # Output: [2, 1]
67 chars
4 lines

These are just a few examples of how to swap elements in an array in Ruby. The specific approach you choose will depend on your specific needs and coding style.

related categories

gistlibby LogSnag