John Gringus
John Gringus

Reputation: 59

How to get only a part of a line for I/O

I am trying to read this in Ruby

4 0.9
51 0.35
6 0.7
5 0.74
52 0.33

Where I want to take the first number in each row and store it in an array and then take the second number (a float) and put it in another array.

However, if I did something like n = inputFile.gets then I would get the entire line. How would I be able to achieve what I want to achieve?

Upvotes: 0

Views: 47

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110755

First create a file with test data.

data =<<END
4 0.9
51 0.35
6 0.7
5 0.74
52 0.33
END

FName = 'test'
File.write(FName, data)
  #=> 35

Now read the file and compute the desired return value.

ai, af = File.readlines(FName).map(&:split).transpose
  #=> [["4", "51", "6", "5", "52"], ["0.9", "0.35", "0.7", "0.74", "0.33"]]
[ai.map(&:to_i), af.map(&:to_f)]
  #=> [[4, 51, 6, 5, 52], [0.9, 0.35, 0.7, 0.74, 0.33]]

Upvotes: 0

7stud
7stud

Reputation: 48649

require 'pp'

data = Hash.new{|hash,key| hash[key] = []} #Instead of returning nil for a non existent key,
                                           #execute hash[new_key] = [] and return the array

File.open('data.txt') do |f|
  while line = f.gets
    col1, col2 = line.split
    data['col1'] << col1
    data['col2'] << col2
  end
end

pp data
p data['col1']

--output:--
{"col1"=>["4", "51", "6", "5", "52"],
 "col2"=>["0.9", "0.35", "0.7", "0.74", "0.33"]}

["4", "51", "6", "5", "52"]

Upvotes: 2

ddavison
ddavison

Reputation: 29092

there is no problem with getting the entire line, you can just split it. try this:

first_nums = []
second_nums = []
input_file = File.open('file.in').read
input_file.each_line do |line|
  num1, num2 = line.split(' ')
  first_nums << num1
  second_nums << num2
end

first_nums #=> [4, 51, 6, 5, 52]
second_nums #=> [0.9, 0.35, 0.7, 0.74, 0.33]

if you absolutely need to use gets, then you can try this

first_nums = []
second_nums = []
while (line = inputFile.gets) do
   num1, num2 = line.split(' ')
   first_nums << num1
   second_nums << num2
end

Upvotes: 2

Related Questions