Manipulate . txt file and put it into a Ruby array

Asked

Viewed 1,086 times

3

I need, from a file . txt that has multiple tweets (one on each line), to read this file and put in a variable in the following format:

[1, "texto da primeira linha do arquivo"], [1, "texto da segunda linha"]

I was able to read the file and print it, but I cannot mount array array.

1 answer

3


You can use the method readlines

tweets = IO.readlines('filename.txt')
puts tweets[0] # => "primeiro tweet"

But if you want an array identical to the one you requested, do so:

tweets = IO.readlines('filename.txt').each_with_index.map do |line, line_num|
  [line_num, line]
end
puts tweets[0] # => [0, "primeiro tweet"]
  • Thank you very much! Just a brief question. What does . map mean?

  • The map is very common in programming languages, and what it does is return each execution of the block within an array. For example: [1, 2, 3].map {|number| number * 2 } # => [2, 4, 6]

  • Got it! And what’s the difference for . each?

  • each does not return anything, using the previous example: [1, 2, 3].each {|number| number * 2 } # => [1, 2, 3]. To reproduce the result of map using the each you would have to do + or - like this: tmp = []; [1, 2, 3].each {|number| tmp << number * 2 }; puts tmp # => [2, 4, 6]. See more here: http://stackoverflow.com/questions/5254128/arrayeach-vs-arraymap

  • Thanks for the answers (:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.