How do i split a file by newline

A

Amit Tomar

Hi all,
I would like to know how do i split a file by newline ,am
able to do it tab space like

path="E:/expr/amit.txt"
File.open(path).each do |i|
k=i.split("\t" )

puts "#{k[0]}"
end

o/p: amit

and this is content of my file(amit.txt)

amit sumit

now i changed content of file like

amit
sumit

path="E:/expr/amit.txt"
File.open(path).each do |i|
k=i.split("\n" )

puts "#{k[0]}"
end

i should get amit only but am getting
amit
sumit

how do i make them split from newline??
 
U

Une Bévue

Amit Tomar said:
path="E:/expr/amit.txt"
File.open(path).each do |i|
k=i.split("\n" )

puts "#{k[0]}"
end

i should get amit only but am getting
amit
sumit

how do i make them split from newline??

no need to split("\n") because it's allready done :
#! /opt/local/bin/ruby1.9
# encoding: utf-8
k=[]
File.open("amit.txt").each {|l| k<<l }
puts k[0]

here i get amit, the first line.
 
A

Amit Tomar

=?ISO-8859-1?Q?Une_B=E9vue?= wrote in post #950421:
Amit Tomar said:
how do i make them split from newline??

no need to split("\n") because it's allready done :
#! /opt/local/bin/ruby1.9
# encoding: utf-8
k=[]
File.open("amit.txt").each {|l| k<<l }
puts k[0]

here i get amit, the first line.

Thanks frnd
but why split("\n") is not working for me
 
U

Une Bévue

Amit Tomar said:
but why split("\n") is not working for me

i think because the :
File.open("amit.txt").each {|l| k<<l }
allready split the content of the file by line, then, no more \n ?
the ".each" here would means each line...
 
R

Robert Klemme

2010/10/15 Une B=E9vue said:
Amit Tomar said:
path=3D"E:/expr/amit.txt"
File.open(path).each do |i|
k=3Di.split("\n" )

puts =A0"#{k[0]}"
end

i should get amit only but am getting
amit
sumit

how do i make them split from newline??

no need to split("\n") because it's allready done :
#! /opt/local/bin/ruby1.9
# encoding: utf-8
k=3D[]
File.open("amit.txt").each {|l| k<<l }
puts k[0]

Even simpler

k =3D File.readlines "amit.txt"
# different separator
# k =3D File.readlines "amit.txt", "\t"

Cheers

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top