OneBite.Dev - Coding blog in a bite size

swap a string in Ruby

Code snippet on how to swap a string in Ruby

string1, string2 = "Hello", "World"
string1, string2 = string2, string1

puts "String 1 is: #{string1}"
puts "String 2 is: #{string2}"

This code swaps two strings. It begins by declaring two variables, string1 and string2. They are set to the strings “Hello” and “World”, respectively.

Next, the two variables are swapped using a single line of code. This is possible due to the multiple assignment syntax available in Ruby. This means that we can assign more than one variable in a single line. Here, we are swapping string1 and string2.

Finally, the code prints out the two strings with a statement for each. This shows the swap was successful. String1 is now World and String2 is now Hello.

ruby