Chuck Smithson Chuck Smithson - 1 year ago 87
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.

class Integer
def to_base(b)
while n > 0
n = n/b
def to_oct

puts "Enter a number: "
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 Source

As suggested, do something like this:

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

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

 5.to_base 2 #=> "101"
65.to_oct    #=> "101"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download