ruby 将数组的内容转换为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8036809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:28:16  来源:igfitidea点击:

Convert contents of an array to int

rubyinttype-conversion

提问by Benoit Garret

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_imethod?

此代码读入文件并将其放入二维数组中。现在我需要获得数组中所有数字的平均值,但我需要将数组的内容更改为 int。任何想法把to_i方法放在哪里?

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

回答by Benoit Garret

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:

或使用以下内容,正如Marc-André在评论中亲切指出的那样:

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

回答by Bhushan Lodha

did you try

你试过了吗

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