4

I'm trying to read numbers from a txt file into an array in ruby with some conditions. The text file input looks like this:

1 2 3 4
5 6 7 8
9;10 11 12

What I want to do is read the numbers up to ';', store them in array, execute a method on that array, and then clear the array and start reading from the semicolon again. Here you can see the execution of the program with the input seen above:

read [1,2,3,4,5,6,7,8,9] -> Execute method X -> [] Clear array -> [10 11 12] -> execute method X...

I think a variation of the following code would do the trick, but I don't know enough ruby to do this myself.

 a = []
 File.open('names.txt') do |f|
   f.each_line do |line|
     a << line.split.map(&:to_i)
   end
 end

Thanks for your help! This is for curiosity, not an assignment or anything else. I'm trying to build ruby skills by doing simple things.

3 Answers 3

3

you can do something like this.

f = File.read 'names.txt' 
f.split(';').each  do |set|
  method_x(set.split.map(&:to_i))
end

This assumes method_x takes an array as an arg.

Sign up to request clarification or add additional context in comments.

Comments

3

I would do as below :

File.readlines('a.txt',';').each do |string|
  ary = string.scan(/\d+/).map(&:to_i)
  method_x(ary)
end

You can put the line separator as ;, as per the documentation readlines(name, sep=$/ [, open_args]) .

Reads the entire file specified by name as individual lines, and returns those lines in an array. Lines are separated by sep.

Comments

0
File.read('names.txt').split(';').each { |x| the_function(x.split.map(&:to_i)) }

where the_function is your desired function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.