-
-
Notifications
You must be signed in to change notification settings - Fork 551
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Reconsiders responsibility of constructor in binary exercise (#499)
binary: Reconsiders responsibility of constructor
- Loading branch information
1 parent
5da1a86
commit f50fa49
Showing
4 changed files
with
33 additions
and
36 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
2 | ||
3 |
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,25 @@ | ||
module BookKeeping | ||
VERSION = 2 | ||
VERSION = 3 | ||
end | ||
|
||
class Binary | ||
attr_reader :digits | ||
def self.to_decimal binary | ||
fail ArgumentError.new("invalid binary input #{binary}") if invalid?(binary) | ||
|
||
def initialize(s) | ||
fail ArgumentError.new("invalid binary input #{s}") unless valid?(s) | ||
|
||
@digits = s.chars.reverse.collect(&:to_i) | ||
digits(binary).reduce(0, &method(:convert)) | ||
end | ||
|
||
def to_decimal | ||
digits.each_with_index.inject(0) do |decimal, (digit, i)| | ||
decimal + digit * 2**i | ||
end | ||
private | ||
|
||
def self.invalid?(binary) | ||
binary =~ /[^01]/ | ||
end | ||
|
||
private | ||
def self.digits(binary) | ||
binary.chars.map(&:to_i) | ||
end | ||
|
||
def valid?(s) | ||
s.chars.all? { |char| ['0', '1'].include?(char) } | ||
def self.convert(decimal, digit) | ||
decimal * 2 + digit | ||
end | ||
end |
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