0

I have the following 3x3 array:

grid = [["1","2","3"],["4","5","6"],["7","8","9"]]

I want to convert each number from a String to a Fixnum. I tried:

grid.each{ |thing| thing.each { |subthing| subthing = subthing.to_i }}

However, puts grid[0][0].class still outputs String.

1 Answer 1

2

each just iterates over each value, it doesn't change the contents. Try using map.

foo = grid.map{ |a| a.map(&:to_i) }  # foo => [[1,2,3,],[4,5,6],[7,8,9]], but grid is still the original

If you want to update grid in place:

grid.each { |a| a.map!(&:to_i) }
Sign up to request clarification or add additional context in comments.

1 Comment

Slightly more efficient: grid.each { |a| a.map!(&:to_i) }. No need need to make new inner arrays, just replace their elements in place with Array#map!.

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.