Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New lines list into array

Tags:

arrays

list

ruby

I have a list containing new lines and I like to convert it into an array, e.g.

JAN 

FEB 

MAR

APR

MAY

into ["JAN", "FEB", "MAR", "APR", "MAY]

Any help will be appreciated. Thanks

Something like this doesn't seem to work (text_file.txt contains a list of months as above)

file = File.new("text_file.txt", "r")
while (line = file.gets)
    line.chomp 
    list = line.split(/\n/)
    puts "#{list}"
end
like image 378
Mark Avatar asked Nov 29 '11 11:11

Mark


4 Answers

I realize this question is several years old, but I was unable to create an array with the other answers. I was able to figure it out by using the following code. (My list was separated by a return and not a newline.)

For data separated by a return:

text = []

input = File.read("x_values.txt")
  text = input.split("\r")
puts text.to_s

If you want to split on a newline instead:

text = []
input = File.read("x_values.txt")
  text = input.split("\n")
puts text.to_s
like image 94
Melanie Shebel Avatar answered Nov 03 '22 12:11

Melanie Shebel


This works on 1.9.. not sure if empty? is available in 1.8 though

%(
JAN 

FEB 

MAR

APR

MAY
).split(/\n/).reject(&:empty?)
like image 32
Derek Ekins Avatar answered Nov 03 '22 11:11

Derek Ekins


If you mean this kind of list

text = "JAN\nFEB\nMAR\nAPR\nMAY"

then you can convert it to array like this

text.split(/\n/) => ["JAN", "FEB", "MAR", "APR", "MAY"]

UPDATE: Second try:

text = []
File.read("text_file.txt").each_line do |line|
  text << line.chop
end
puts text => ["JAN", "FEB", "MAR", "APR", "MAY"]
like image 39
megas Avatar answered Nov 03 '22 12:11

megas


I found michalfs one-line solution very helpful, though I'd like to note a subtle detail (which will probably be only interesting to ruby-newbies like myself).

If the Y of MAY is the last character in the textfile, the resulting array will look like this:

["JAN", "FEB", "MAR", "APR", "MA"]

Why so? Quoting from the String#chop ruby doc:

chop → new_str Returns a new String with the last character removed. [...] String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn’t end in a record separator.

Therefore chomp seems to be more accurate in this particular case:

File.readlines("text_file.txt").map{ |l| l.chomp }.reject{ |l| l == '' }

(Yes, I only added the 'm' to michalfs solution.)

like image 30
nischi Avatar answered Nov 03 '22 12:11

nischi