Chuck Smithson Chuck Smithson - 12 days ago 5
Ruby Question

Convert Integer to Octal using class Integer and multiple methods

I have a script started but am receiving an error message. I typically have the right idea, but incorrect syntax or formatting.

Here are the exact instructions given:

Extend the Integer class by adding a method called to_oct which returns a string representing the integer in octal. We'll discuss the algorithm in class. Prompt the user for a number and output the octal string returned by to_oct.

Add another method to your Integer extension named "to_base". This method should take a parameter indicating the base that the number should be converted to. For example, to convert the number 5 to binary, I would call 5.to_base(2). This would return "101". Assume that the input parameter for to_base is an integer less than 10. to_base should return a string representing the decimal in the requested number base.

#!/usr/bin/ruby
class Integer
def to_base(b)
string=""
while n > 0
string=(n%b)+string
n = n/b
end
end
def to_oct
n.to_base(8)
end
end

puts "Enter a number: "
n=gets.chomp
puts n.to_base(2)


When I run the script I do get the enter a number prompt, but then I get this error message:

tryagain.rb:16:in `<main>': undefined method `to_base' for "5":String (NoMethodError)

Answer

As suggested, do something like this:

class Integer
  def to_base b
    to_s b       #same as self.to_s(b)
  end

  def to_oct
    to_base 8    #same as self.to_base(8)
  end
end

 5.to_base 2 #=> "101"
65.to_oct    #=> "101"
Comments