2017-03-04 50 views
1

下面的代碼旨在取整數,每個數字平方,並返回整數與平方數字。Ruby:未定義的方法`數字'爲3212:Fixnum(NoMethodError)

不過,我一直有這個錯誤:

`square_digits': undefined method `digits' for 3212:Fixnum (NoMethodError) 
    from ` 
' 

我不明白爲什麼我有這個錯誤的.digits方法是在Ruby中包含的方法,我用它上一個整數,但它給了我一個NoMethodError。

def square_digits(digit) 

    puts digit 
    puts digit.inspect 
    puts digit.class 

    if digit <= 0 
    return 0 
    else 
    #converts the digit into digits in array 
    split_digit = digit.digits 
    puts "split digit class and inspect" 
    puts split_digit.inspect 
    puts split_digit.class 

    # multiples each digit by itself 
    squared = split_digit.map{ |a| a * a} 
    squared.reverse! 

    # makes digits into string 
    string = squared.join('') 

    # converts string into integer 
    string.to_i 
    end 

end 

有誰知道發生了什麼事?

+1

你使用的是什麼版本的Ruby? AFAIK'整數#位數'來自Ruby 2.4(最新版本)。 –

+0

我在我的計算機上使用了最新版本,但代碼正在另一臺計算機上運行。我不知道他們的紅寶石的版本。這可能是問題所在。 – alucinare

回答

4

我想你使用的是比2.4.0更老的Ruby版本。如果是這樣,那麼這種方法將不可用。它在2.4.0中加入。看到這個link

要添加對你老ruby版本的支持,你可以在你的方法定義之前添加下面的代碼。

class Integer 
    def digits(base: 10) 
    quotient, remainder = divmod(base) 
    quotient == 0 ? [remainder] : [*quotient.digits(base: base), remainder] 
    end 
end 

添加此代碼段後,您應該可以運行您的方法。

+1

用保護代碼來保護這個墊片會更好,這樣你就不需要重新定義它,或者把方法放在你自己的模塊中,而不是使用'Integer#digits'插槽。 –

相關問題