Created
June 2, 2015 15:24
-
-
Save anonymous/0e36f055a967c68900b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pry -r'./lib/binary' | |
#[1] pry(main)> Binary.new('foo').to_decimal | |
#=> 0 | |
#[2] pry(main)> Binary.new('01010').to_decimal | |
#=> 10 | |
#[3] pry(main)> Binary.new('foo110').to_decimal | |
#=> 0 | |
class Binary | |
attr_accessor :number | |
def initialize(number) | |
@number = number | |
end | |
def to_decimal | |
return 0 unless @number[/^[01]+/] | |
binary_to_decimal | |
end | |
private | |
def binary_to_decimal | |
number_array.each_with_index.inject(0) do |results, (obj, index)| | |
results += power_of_two_array[index] if obj == 1 | |
results | |
end | |
end | |
def power_of_two_array | |
(0..number_array.size - 1).to_a.map { |e| 2**e }.reverse | |
end | |
def number_array | |
@number.to_s.each_char.map(&:to_i) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment