New lines list into array
Solution 1
This works on 1.9.. not sure if empty? is available in 1.8 though
%(
JAN
FEB
MAR
APR
MAY
).split(/\n/).reject(&:empty?)
Solution 2
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"]
Solution 3
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
Solution 4
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.)
Mark
Updated on June 13, 2022Comments
-
Mark almost 2 years
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
-
Mark over 12 yearsNope, this doesnt seem to work either. I get back the same list.
-
megas over 12 yearsThe 'text' variable contains the result, if you want to store result to file, you should write result to file.
-
Clone over 11 yearshow do you do if I have a line
JAN 01
FEB 02
I want to store month names and their number in different arrays? -
Clone over 11 yearsin other words how to strip the
tab
in each line. -
fny over 11 years@Clone by matching with regular expressions
-
Franco Rondini about 11 years+1 I tested it, working without trouble on 1.8.7; 1.9.3; 2.0.0
-
Cary Swoveland almost 8 yearsI suggest a small change to the regex to deal with "empty" lines:
/\n\n*/
. -
Petr Bela over 7 yearsYou can also use
/\n+/