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
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
This works on 1.9.. not sure if empty? is available in 1.8 though
%(
JAN
FEB
MAR
APR
MAY
).split(/\n/).reject(&:empty?)
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"]
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With