BinaryChar
is a class with one method. You continually change the state of the object so you can call the method with the right "argument". That's not what classes are for, but module functions or class methods. I rewrote the code twice: once using a class in the right way and once using a module function (or class method).
with a class
class BinaryChar
def initialize(string)
@binary = string.scan(/.{1,8}/).map do |character|
character.to_i(2).chr
end
end
def to_s
@binary.join
end
end
loop do
print "Enter string: "
bc = BinaryChar.new(gets)
puts bc # to_s is called automatically by puts.
end
with a module function
module Binary
def self.to_binary(string)
binary = string.scan(/.{1,8}/).map do |character|
character.to_i(2).chr
end
binary.join
end
end
loop do
print "Enter string: "
puts Binary.to_binary
end
A couple of minor nitpicks:
- In ruby the convention is to use
snake_case
for anything but ClassNames
and CONSTANTS
.
- When you get input from stdin (
gets
) a newline is appended to it ("\n"
). In most cases you want to strip the newline of using String#chomp
.
- Accessor methods can look just like variable assignments:
bc.binary_string = speak
.
- Conversion methods are usually named
to_<something>
. To convert to a String
, for example, most classes implement a to_s
method.