简体   繁体   中英

trying to add .dat file contents to a 2d array in ruby.

I'm trying to read this .dat file and then add the content to a 2d array.

Sean 20000.0 5000.0
John 60000.0 5000.0
Patricia 50000.0 7000.0
Lucy 80000.0 4000.0
Marie 34000.0 6800.0
Michael 42000.0 3000.0
Aoife 22000.0 5000.0
Barry 10000.0 4000.0
Angela 65000.0 6000.0
Luke 35000.0 4000.0
Ciara 8000 5000
Sean 200000.0 5000.0

This is the code I have so far but it gives me an error on the gets method.

class Taxpayer

  def initialize filename
    @input = IO.readlines(filename)
    @info=[]
    end

  def set_up
   size = @input.length

    i = 0
    while i < size
        @info << (@input.gets).split(' ')
    end
  end
end

Each element of your @input array is a String, so if you want to store each row as an array, you need to pop each row off @input, split them along whitespaces, and then store that array as a new element of @info, like this:

@input.each do |x|
    row = x.split
    @info << row
end

Keep in mind that each element of each of your new inner arrays will be Strings, so you'll want to convert the last two elements of each array to floats as well if you want to use them later.

I recommend you use the csv library from ruby. Just specify :col_sep as blank in options

CSV.foreach(path, 'r', :col_sep => ' ') do |row|
  ...
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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