2016-11-24 77 views
2

我有一個腳本已啓動,但正在接收一條錯誤消息。我通常有正確的想法,但語法或格式不正確。使用類Integer和多種方法將整數轉換爲Octal

下面是給出的確切指令:
通過添加一個名爲to_oct的方法來擴展Integer類,該方法返回一個表示八進制整數的字符串。我們將在課堂上討論算法。提示用戶輸入一個數字並輸出由to_oct返回的八進制字符串。

將另一個方法添加到名爲「to_base」的Integer擴展中。此方法應該帶有一個參數,指示數字應該轉換爲的基數。例如,要將數字5轉換爲二進制,我將調用5.to_base(2)。這將返回「101」。假設to_base的輸入參數是一個小於10的整數。to_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) 

當我運行該腳本,我得到了輸入號碼的提示,但後來我得到這個錯誤信息:

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

你禁止使用[Fixnum#to_s](http://ruby-doc.org//core-2.3.0/Fixnum.html#method-i-to_s)?如果不是,那就是要走的路。你的第五行應該是'n = gets.to_i'(或'n = gets.chomp.to_i')。我會重新格式化你的代碼。 –

+0

沒有額外的限制 –

回答

0

至於建議,做這樣的事情:

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" 
+0

這正是我需要幫助完成這項工作。感謝一堆Cary和sagarpandy –

相關問題