Skip to content

Instantly share code, notes, and snippets.

@broguinn
Created August 29, 2013 00:55
Show Gist options
  • Save broguinn/6373150 to your computer and use it in GitHub Desktop.
Save broguinn/6373150 to your computer and use it in GitHub Desktop.
binary
def binary(binary_string)
if !(binary_string.is_a?(String)) || binary_string.match(/[^0,1]/)
raise TypeError.new("Input must be only 0s and 1s")
end
total = 0
binary_string.reverse.split("").each_with_index do |bit, index|
total += bit.to_i * 2 ** index
end
total
end
def trinary(trinary_string)
if !(trinary_string.is_a?(String)) || trinary_string.match(/[^0,1,2]/)
raise TypeError.new("Input must be only 0s and 1s and 2s")
end
total = 0
trinary_string.reverse.split("").each_with_index do |bit, index|
total += bit.to_i * 3 ** index
end
total
end
def binary(binary_string)
if !(binary_string.is_a?(String)) || binary_string.match(/[^0,1]/)
raise TypeError.new("Input must be only 0s and 1s")
end
total = 0
binary_string.reverse.split("").each_with_index do |bit, index|
total += bit.to_i * 2 ** index
end
total
end
def trinary(trinary_string)
if !(trinary_string.is_a?(String)) || trinary_string.match(/[^0,1,2]/)
raise TypeError.new("Input must be only 0s and 1s and 2s")
end
total = 0
trinary_string.reverse.split("").each_with_index do |bit, index|
total += bit.to_i * 3 ** index
end
total
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment