user1027502
user1027502

Reputation:

Convert contents of an array to int

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

This code reads in the file and puts it into 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 where to put 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

Upvotes: 6

Views: 23876

Answers (2)

Benoit Garret
Benoit Garret

Reputation: 13675

Just map your array to integers:

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

side note

If you want to get the average of a line, 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é kindly pointed out in the comments:

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

Upvotes: 12

Bhushan Lodha
Bhushan Lodha

Reputation: 6862

did you try

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

Upvotes: -2

Related Questions