下面的代码用于获取整数,每个数字的平方,并返回带有平方数字的整数.
但是,我一直有这个错误:
`square_digits': undefined method `digits' for 3212:Fixnum (NoMethodError)
from `
'
Run Code Online (Sandbox Code Playgroud)
我不明白为什么我有这个错误,因为.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
Run Code Online (Sandbox Code Playgroud)
有谁知道发生了什么?
我猜你使用的是旧版本的Ruby而不是2.4.0.如果是这样,则此方法将不可用.它在2.4.0中添加.看到这个链接
要添加对旧ruby版本的支持,您只需在方法定义之前添加以下代码即可.
class Integer
def digits(base: 10)
quotient, remainder = divmod(base)
quotient == 0 ? [remainder] : [*quotient.digits(base: base), remainder]
end
end
Run Code Online (Sandbox Code Playgroud)
添加此代码段后,您应该能够运行您的方法.
| 归档时间: |
|
| 查看次数: |
896 次 |
| 最近记录: |