How to Read Lines of a File in Ruby

How to read lines of a file in Ruby

I believe my answer covers your new concerns about handling any type of line endings since both "\r\n" and "\r" are converted to Linux standard "\n" before parsing the lines.

To support the "\r" EOL character along with the regular "\n", and "\r\n" from Windows, here's what I would do:

line_num=0
text=File.open('xxx.txt').read
text.gsub!(/\r\n?/, "\n")
text.each_line do |line|
print "#{line_num += 1} #{line}"
end

Of course this could be a bad idea on very large files since it means loading the whole file into memory.

Ruby - Read file and print line number

Ruby, like Perl, has the special variable $. which contains the line number of a file.

File.open("file.txt").each do |line|
puts line, $.
end

Prints:

#Hello
1
#My name is John Smith
2
#How are you?
3

Strip the \n from line if you want the number on the same line:

File.open("file.txt").each do |line|
puts "#{line.rstrip} #{$.}"
end

#Hello 1
#My name is John Smith 2
#How are you? 3

As stated in comments, rather than use File.open you can use File.foreach with the benefit of autoclose at the end of the block:

File.foreach('file.txt') do |line|
puts line, $.
end
# same output...

How to read lines from file into array?

Do as below :

File.readlines('test.txt')

Read documentation :

arup@linux-wzza:~> ri IO::readlines

= IO::readlines

(from ruby site)
------------------------------------------------------------------------------
IO.readlines(name, sep=$/ [, open_args]) -> array
IO.readlines(name, limit [, open_args]) -> array
IO.readlines(name, sep, limit [, open_args]) -> array

------------------------------------------------------------------------------

Reads the entire file specified by name as individual lines, and
returns those lines in an array. Lines are separated by sep.

a = IO.readlines("testfile")
a[0] #=> "This is line one\n"

If the last argument is a hash, it's the keyword argument to open. See IO.read
for detail.

Example

arup@linux-wzza:~/Ruby> cat out.txt
name,age,location
Ram,12, UK
Jadu,11, USA
arup@linux-wzza:~/Ruby> ruby -e "p File::readlines('./out.txt')"
["name,age,location\n", "Ram,12, UK\n", "Jadu,11, USA\n"]
arup@linux-wzza:~/Ruby>

Ruby want to read file line by line and get the particular part out using gsub

Strings Don't Normally #respond_to? :each

The stack trace tells you everything you need to know:

undefined method `each' for #String:0x00007fef3d0907c0 (NoMethodError)

Even assuming that /channels / with a trailing space is a valid portion of the file path, File#open returns a File object rather than a collection of lines. As written, video_links is a String, not a collection such as a Hash or Array, and there's no String#each method. Since for-in loops are syntatic sugar for #each, the object can't respond to the method.

Depending on whether you want to slurp the whole file into an array of lines, or operate linewise, you should use one of the following alternative methods:

  1. File#each_line, inhereted from IO. For example:

    File.open("path/to/file").each_line
  2. File#readlines, also inherited from IO. For example:

    File.readlines("path/to/file")

Reading the first line of a file in Ruby

This will read exactly one line and ensure that the file is properly closed immediately after.

strVar = File.open('somefile.txt') {|f| f.readline}
# or, in Ruby 1.8.7 and above: #
strVar = File.open('somefile.txt', &:readline)
puts strVar

Ruby - how to read first n lines from file into array

Here is a one-line solution:

lines = File.foreach('file.txt').first(10)

I was worried that it might not close the file in a prompt manner (it might only close the file after the garbage collector deletes the Enumerator returned by File.foreach). However, I used strace and I found out that if you call File.foreach without a block, it returns an enumerator, and each time you call the first method on that enumerator it will open up the file, read as much as it needs, and then close the file. That's nice, because it means you can use the line of code above and Ruby will not keep the file open any longer than it needs to.

How do I read the nth line of a file efficiently in Ruby?

What about IO.foreach?

IO.foreach('filename') { |line| p line; break }

That should read the first line, print it, and then stop. It does not read the entire file; it reads one line at a time.



Related Topics



Leave a reply



Submit