3

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)
3
  • Are you prohibited from using Fixnum#to_s? If not, that's the way to go. Your pentultimate line should be n = gets.to_i (or n = gets.chomp.to_i). I'll reformat your code for you. Commented Nov 24, 2016 at 0:46
  • There were no extra limitations Commented Nov 24, 2016 at 0:48
  • 1
    Just use the builtin method call n.to_s(8) Commented Feb 24, 2023 at 2:24

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I needed to help make this work. Thanks a bunch Cary and sagarpandy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.