Ruby中to_i转换无效求助:整数反转存入数组失败
Hey there! Let's break down what's going wrong with your code and fix it step by step.
Core Problem in Your Code
The main issue is that you're calling item.to_i but not saving the converted integer back to the array. The to_i method returns a new integer value, but it doesn't modify the original string element in your answer array. You're just printing the converted value, leaving the original string elements intact—so when you return answer, it's still an array of strings instead of integers, which fails the test.
On top of that, your code has unnecessary complexity: nested method definitions, redundant type checks (like Array(answer) unless answer.is_a? Integer—since n.to_s.split(//).reverse! already returns an array), and messy flow that makes it hard to track the logic.
Fixed, Simplified Code
Let's rewrite this with clean, straightforward logic that does exactly what you need:
def digitize(n) n.to_s.chars.reverse.map(&:to_i) end
If you prefer a more explicit loop-based approach (to match your original code structure and help you understand better), here's a corrected version:
def digitize(n) answer = n.to_s.split(//).reverse # Replace each string element with its integer equivalent answer.map! do |item| item.to_i end answer end
Why Your Original Loop Failed
Look at your original loop code:
for item in answer item.to_i puts item tf(item) end
The item here is a copy of the array element. Calling item.to_i calculates the integer, but doesn't update the actual element in the answer array. That's why your tf method kept printing String: true—the array never got modified to hold integers.
Test It Out
Run your test case again with the fixed code:
Test.assert_equals(digitize(35231),[1,3,2,5,3])
It'll pass now!
内容的提问来源于stack exchange,提问作者Zabieru

