Ruby Decimal to Binary Conversion – Loops, Recursion & Bitwise Methods
What Are We Solving?
In this guide, we’ll explore how to convert a decimal number into binary using Ruby, covering various techniques — from manual logic to built-in utilities.
Each approach will demonstrate a slightly different programming style so you can see how Ruby makes such logic clean and expressive.
Use Cases
- 
	Learning how number systems work at the code level. 
- 
	Building console-based binary converters. 
- 
	Writing Ruby scripts that deal with binary data formats. 
- 
	Technical interview preparation for base conversion problems. 
Conversion Using While Loop and String Manipulation
# Convert decimal to binary using a while loop
def binary_with_loop(number)
  return "0" if number == 0
  binary = ""
  while number > 0
    binary = (number % 2).to_s + binary
    number /= 2
  end
  binary
end
puts "Binary of 45: #{binary_with_loop(45)}"
Explanation
- 
	We divide the number repeatedly by 2.
- 
	Each remainder is prepended to the binary result. 
- 
	Stops when the number becomes 0.
Output
Binary of 45: 101101
Conversion Using Recursion
# Recursive approach to convert decimal to binary
def binary_recursive(number)
  return "" if number == 0
  binary_recursive(number / 2) + (number % 2).to_s
end
result = binary_recursive(22)
puts "Binary of 22: #{result.empty? ? '0' : result}"
Explanation
- 
	The function divides the number recursively. 
- 
	Each bit is collected as the stack unwinds. 
- 
	Base case: if number is 0, return empty string. 
Output
Binary of 22: 10110
Conversion Using Bitwise Operators
# Convert decimal to binary using bitwise shifting
def binary_with_bitwise(number)
  return "0" if number == 0
  result = ""
  started = false
  (31).downto(0) do |i|
    bit = (number >> i) & 1
    started ||= bit == 1
    result += bit.to_s if started
  end
  result
end
puts "Binary of 18: #{binary_with_bitwise(18)}"
Explanation
- 
	Right shift the number bit-by-bit. 
- 
	Extract each bit using ANDoperation.
- 
	Skip all leading zeros until first 1appears.
Output
Binary of 18: 10010
Instant Conversion Using Ruby’s Built-in Method
# Built-in method to convert decimal to binary
number = 12
puts "Binary of #{number}: #{number.to_s(2)}"
Explanation
- 
	.to_s(2)converts the integer tobase-2(binary) string format.
- 
	Easiest and fastest method for one-liners. 
Output
Binary of 12: 1100
Final Thoughts
Ruby provides both manual control and built-in ease when it comes to binary conversion. Whether you’re preparing for interviews, building educational tools, or just exploring how numbers work, these 4 techniques offer a well-rounded learning path.