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

Are these two expressions delivering the same result?

I'm trying to get my head around some basic Ruby syntax and was wondering whether example #1 is equivalent of example #2 below. And if so what are the pros and cons of each method?

Option #1 myfile = File.open('file.txt', "w") myfile.puts('Hello everybody')

Option #2 File.open('file.txt', "w") do |myfile| puts('Hello everybody') end

2 Answers

Kenan Memis
Kenan Memis
47,314 Points

Hi,

First of all, both options do not write anything to the file you want to create. When you use File.open() you have to close the file. Also Option2 syntax is not correct.

I guess you want to obtain the following solutions and yes, both are equivalent:

Option1:

myfile = File.open('file.txt', "w")
myfile.puts('Hello everybody')
myfile.close

Option2:

File.open('file.txt', "w") do |myfile|
  myfile.puts('Hello everybody')
  myfile.close
end

If you want to simplify Option2 you can use write method of File class without using close method. But in Option1 syntax you definetely should use close method:

File.open('file.txt', "w") do |myfile|
  myfile.write('Hello everybody')
end

Thanks for this! I assumed the syntax was a bit off, just trying to get my head around variables created on the fly in Ruby on a conceptual level.