Skip to content

Instantly share code, notes, and snippets.

@Nitesh-Mishra
Created September 11, 2017 19:21
Show Gist options
  • Select an option

  • Save Nitesh-Mishra/8a04c709cfeed73d935faa2516a84b6e to your computer and use it in GitHub Desktop.

Select an option

Save Nitesh-Mishra/8a04c709cfeed73d935faa2516a84b6e to your computer and use it in GitHub Desktop.
Swapping two variables in ruby
#Swapping two variables in ruby :
#
# $ ruby swap_two_variables.rb
# Enter first variable :
# 2
# Enter second variable :
# 3
# After exchanging the value :
# the value of a is :3
# the value of b is :2
# the value of a is :2
# the value of b is :3
# the value of a is :3
# the value of b is :2
puts "Enter first variable :"
a = gets.to_i
puts "Enter second variable :"
b = gets.to_i
puts "the value of a is :#{a}"
puts "the value of b is :#{b}"
puts "After exchanging the value :"
# Ist method
a,b = b,a
puts "the value of a is :#{a}"
puts "the value of b is :#{b}"
#2nd method using temperory variable
c = a
a = b
b = c
puts "the value of a is :#{a}"
puts "the value of b is :#{b}"
#3rd method using arithmetic operation
a = a+b
b = a-b
a = a-b
puts "the value of a is :#{a}"
puts "the value of b is :#{b}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment