rubycode-golf

Ruby read/write to file in 1 line of code


I am kind of a newbie to Ruby, I am working out some katas and I stuck on this silly problem. I need to copy the content of 1 file to a new file in 1 line of code

First try:

File.open(out, 'w').write(File.open(in).read)

Nice, but it's wrong I need to close the files:

File.open(out, 'w') { |outf| outf.write(File.open(in).read) }

And then of course close the read:

File.open(out, 'w') { |outf| File.open(in) { |inf| outf.write(outf.read)) } }

This is what I come up with, but it does not look like 1 line of code to me :(

Ideas?

Regards,


Solution

  • There are many ways. You could simply invoke the command line for example:

    `cp path1 path2`
    

    But I guess you're looking for something like:

    File.open('foo.txt', 'w') { |f| f.write(File.read('bar.txt')) }