Ruby read file example - read a file as a string

Here's a Ruby "read file" example program that shows how to read a file as one string. You just have to pass a file name in to the get_file_as_string method, and this Ruby method will read in all the records from the file, and return the contents of the file as a string.

def get_file_as_string(filename)
  data = ''
  f = File.open(filename, "r") 
  f.each_line do |line|
    data += line
  end
  return data
end

##### MAIN #####

xml_data = get_file_as_string 'Pizza.hbm.xml'

# print out the string
puts xml_data

As you can see from this example, I'm using this method to read in a Hibernate XML configuration file, which I'm about to parse. However, in this example I'm just using puts to write the file out to my screen to make sure I'm reading it correctly (instead of parsing it using an XML parser, which I hope to show shortly).

I think this will work even

I think this will work even better:

IO.readlines('filename.txt','').to_s

Just use Ruby File.read(path)

You can also just use File.read(path). I don't know why it's not listed in the Ruby File class doc (http://www.ruby-doc.org/core/classes/File.html), but it works.

File.read is listed in the IO

File.read is listed in the IO class. The File class can act like an IO object sometimes.

Or IO.read('filename.txt').

Or IO.read('filename.txt').

Post new comment

The content of this field is kept private and will not be shown publicly.