简体   繁体   English

如何读取Ruby循环中每次迭代的数字?

[英]How to read by the number at each iteration of the loop in Ruby?

How to read by the number at each iteration of the loop? 如何在循环的每次迭代中读取数字? Dynamic work is important, (not once to read the entire line and convert to an array), at each iteration, take one number from the file string and work with it. 动态工作很重要(不是一次读取整行并转换为数组),在每次迭代时,从文件字符串中取一个数字并使用它。 How to do it right? 怎么做对了?

input.txt : input.txt:

5
1 7 5 2 3 

Work with 2nd line of the file. 使用文件的第二行。

fin     = File.open("input.txt", "r")
fout    = File.open("output.txt", "w")
n       = fin.readline.to_i

heap_min = Heap.new(:min)
heap_max = Heap.new(:max)

for i in 1..n

    a = fin.read.to_i #code here <-- 

    heap_max.push(a)
    if heap_max.size > heap_min.size
        tmp = heap_max.top
        heap_max.pop
        heap_min.push(tmp)
    end 
    if heap_min.size > heap_max.size
        tmp = heap_min.top
        heap_min.pop
        heap_max.push(tmp)
    end 
    if heap_max.size == heap_min.size
        heap_max.top > heap_min.top ? median = heap_min.top : median = heap_max.top
    else
        median = heap_max.top
    end
    fout.print(median, " ")
end

Read the 2nd line of a file: 阅读文件的第二行:

line2 =  File.readlines('input.txt')[1]

Convert it to an array of integers: 将其转换为整数数组:

array = line2.split(' ').map(&:to_i).compact

如果您100%确定您的文件按空格分隔数字,您可以尝试这样做:

a = fin.gets(' ', -1).to_i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM