User Program Communication

Read from Text File in Ruby

Used to read from a text file.


Syntax
#for very short files
variable = File.read(file_name)

#to read a file, line by line
File.foreach(file_name) do |line|
  puts line #or any action with line
end

#to open file and do your own action
File.open(file_name) do |openedFile|
    #action
end

Notes

A file object can be created from the File class and assigned to an identifier. In this case, the object must be closed after use to prevent memory leaks.


Example
File.foreach( 'grades.txt' ) do |grade|
    puts "Student mark: #{grade}"
end

See Also
Documentation

RubyDoc - File API

Add to Slack

< Commenting   |   Write to File >

© 2019 SyntaxDB. All Rights Reserved.