Convert array contents to int

I need to read in a file that contains a list of numbers.

This code is read in a file and puts it in a 2d array. Now I need to get the average of all the numbers in my array, but I need to change the contents of the array to int. Any ideas you should use the to_i method?

 Class Terrain def initialize file_name @input = IO.readlines(file_name) #read in file @size = @input[0].to_i @land = [@size] x = 1 while x <= @size @land << @input[x].split(/\s/) x += 1 end #puts @land end end 
+4
source share
2 answers

Just map the array to integers:

 @land << @input[x].split(/\s/).map(&:to_i) 

side note

If you want to get the average value of a string, you can do the following:

 values = @input[x].split(/\s/).map(&:to_i) @land << values.inject(0.0) {|sum, item| sum + item} / values.size 

or use the following, as Marc-AndrΓ© has kindly indicated in the comments:

 values = @input[x].split(/\s/).map(&:to_i) @land << values.inject(0.0, :+) / values.size 
+10
source

You tried

 @land << @input[x].split(/\s/).strip.to_i 
-3
source

Source: https://habr.com/ru/post/1379994/


All Articles