Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Suprasanna Mishra
Suprasanna Mishra
2,730 Points

In Ruby, why is the format for opening a file open(filename) but closing a file is filename.close?

filename = ARGV.first

txt = open(filename)

puts "Here's your file #{filename}:"

print txt.read

txt.close

I'm wondering why the format for opening a file is open(filename) but then to close it it's txt.close.

Ex. Why isn't it filename.open or close(txt)? How do you know which to use when?

Thanks :)

1 Answer

Hiya,

The filename parameter is a string representing the location of the file to be opened. Passing that URI to the open method returns an instance of an open file. That gets assigned to/stored in the txt variable. This makes txt an open file instance, rather than the path to the file. You can then use methods on that instance, such as close. You can't close the filename as that is just a string representing the location of the data you're accessing. So, you call close on the instance of a file, which is txt.

That's my understanding of it ... I hope it helps.

Steve.

Suprasanna Mishra
Suprasanna Mishra
2,730 Points

Thank you Steve, that makes sense!