Tux
Tux

Reputation: 247

Basic Way to Open Files in Ruby

I'm trying to open local xml file and output its content in terminal.

I've tried this;

puts File.new('file.xml', 'r')

and this;

puts File.open('file.xml', 'r')

output from both is, instead of printing xml file to the screen;

#<File:0x00000000....>

Upvotes: 0

Views: 105

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118261

I would suggest you to use block with File#open method. As with block,you don't need to close the file explicitly.Perform all your task inside the block with the file. The file will be closed automatically,when block will be terminated.

File.open('doc.txt','r') do |file|
  puts file.read
end

# >> ,"11: Agriculture, Forestry, Fishing and Hunting",,
# >> ,,"111: Crop Production",
# >> ,,,"111110: Soybean Farming"
# >> ,,,"111120: Oilseed (except Soybean) Farming"

Upvotes: 1

ncwrch
ncwrch

Reputation: 571

Try this

puts File.read('file.xml')

or

puts File.open('file.xml').read

Documentation: IO.read, IO#read

Upvotes: 4

Related Questions