Skip to content

Instantly share code, notes, and snippets.

@tamouse
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamouse/8705622 to your computer and use it in GitHub Desktop.
Save tamouse/8705622 to your computer and use it in GitHub Desktop.
simple repl that shows binary string to decimal string conversion -- doing conversion by hand.
#!/usr/bin/env ruby
OUTPUT_FORMAT = "%s in decimal is %s"
ERROR_FORMAT = "Argument %s must be a binary string (0 and 1 only)."
def convert(binary_string="")
binary_string = binary_string.to_s
unless binary_string[/\A[01]+\z/]
raise ArgumentError.new ERROR_FORMAT % binary_string.inspect
end
number = 0
binary_string.split('').reverse.each_with_index do |c, i|
number += c.to_i * (2 ** i)
end
number.to_s
end
def idiomatic_convert(binary_string="")
Integer("0b#{binary_string.to_s}")
end
def repl
loop do
print "\nEnter a binary string: (just press return to quit) "
response = gets.chomp
break if response.empty?
print "Manual conversion: "
begin
puts OUTPUT_FORMAT % [response, convert(response)]
rescue ArgumentError => e
puts "ERROR: #{e} (#{e.class})"
end
print "Idiomatic conversion: "
begin
puts OUTPUT_FORMAT % [response, idiomatic_convert(response)]
rescue ArgumentError => e
puts "ERROR: " + (ERROR_FORMAT % response.inspect)
puts " - Exception raised: #{e} (#{e.class}) from #{e.backtrace.first}"
end
end
end
puts "Welcome to the Famouse Binary to Decimal Converter!\n"
repl
puts "\nThanks for playing!"
$ ./bin_to_dec
Welcome to the Famouse Binary to Decimal Converter!
Enter a binary string: (just press return to quit) 1
Manual conversion: 1 in decimal is 1
Idiomatic conversion: 1 in decimal is 1
Enter a binary string: (just press return to quit) 2
Manual conversion: ERROR: Argument "2" must be a binary string (0 and 1 only). (ArgumentError)
Idiomatic conversion: ERROR: Argument "2" must be a binary string (0 and 1 only).
- Exception raised: invalid value for Integer(): "0b2" (ArgumentError) from ./bin_to_dec:21:in `Integer'
Enter a binary string: (just press return to quit) "hello
Manual conversion: ERROR: Argument "\"hello" must be a binary string (0 and 1 only). (ArgumentError)
Idiomatic conversion: ERROR: Argument "\"hello" must be a binary string (0 and 1 only).
- Exception raised: invalid value for Integer(): "0b\"hello" (ArgumentError) from ./bin_to_dec:21:in `Integer'
Enter a binary string: (just press return to quit) 101
Manual conversion: 101 in decimal is 5
Idiomatic conversion: 101 in decimal is 5
Enter a binary string: (just press return to quit) 111
Manual conversion: 111 in decimal is 7
Idiomatic conversion: 111 in decimal is 7
Enter a binary string: (just press return to quit)
Thanks for playing!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment