Module: Converter

Defined in:
lib/binToDec.rb

Class Method Summary collapse

Class Method Details

.binToDec(arg1) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/binToDec.rb', line 2

def self.binToDec(arg1)

  #code written by Tom Dowling (tomgdow)

  #TEST FOR BINARY INPUT
  #my_test will be equal to 1 only if arg1 is a binary number
  my_test = arg1.to_s.split(//).map { |i| i.to_i }.find_all { |value| value > 0 }.inject(:*)

  if my_test ==1
      # Generate a binary number using the "move to the right and double" method
    result = arg1.to_s.split(//).map { |i| i.to_i }.inject(0) { |accumulator, value| (accumulator + value) * 2 }
      #The above result will be double what it should be, so need to divide by 2
    return result/2
  else
    return "!Not binary:  #{arg1}"
  end
end