×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Ruby program to swap two numbers using the Bitwise XOR (^) operator

Last Updated : December 15, 2025

Problem Solution

In this program, we will create two integer variables with some initial values. Then we will interchange the values of variables and print the interchanged values.

Program/Source Code

The source code to swap two numbers using the bitwise XOR (^) operator is given below. The given program is compiled and executed successfully.

# Ruby program to swap two numbers 
# using the Bitwise XOR (^) operator

num1=5
num2=3

print "Number before swapping:\n"
print "num1: ",num1,"\n"
print "num2: ",num2,"\n"

num1 = num1 ^ num2
num2 = num1 ^ num2
num1 = num1 ^ num2

print "\nNumber after swapping:\n"
print "num1: ",num1,"\n"
print "num2: ",num2,"\n"

Output

Number before swapping:
num1: 5
num2: 3

Number after swapping:
num1: 3
num2: 5

Explanation

In the above program, we created two integer variables num1, num2 that are initialized with 5, 3 respectively. Then we interchanged the values of variables using the XOR (^) operator and printed the result using the print() function.

Ruby Basic Programs »


Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.