Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby read/write to file in 1 line of code

Tags:

ruby

code-golf

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,

like image 628
Calin Avatar asked Sep 18 '11 20:09

Calin


People also ask

How can you read an entire file and get each line in Ruby?

Use File#readlines to Read Lines of a File in Ruby Newline character \n may be included in each line. We must be cautious when working with a large file, File#readlines will read all lines at once and load them into memory.

How do you edit a .RB file?

An RB file is a software program written in Ruby, an object-oriented scripting language. Ruby is designed to be simple, efficient, and easy to read. RB files can be edited with a text editor and run using Ruby. Ruby is available in several different versions, or "gems," including Ruby on Rails, Mongrel, and Capistrano.

How do I read a .RB file?

You probably have to run the file using the ruby interpreter. I think it would be something like ruby lab7. rb . The output would only show in a browser window if the script is going to be handled by a server process.


2 Answers

Ruby 1.9.3 and later has a

File.write(name, string, [offset], open_args)

command that allows you to write a file directly. name is the name of the file, string is what you want to write, and the other arguments are above my head.

Some links for it: https://github.com/ruby/ruby/blob/ruby_1_9_3/NEWS , http://bugs.ruby-lang.org/issues/1081 (scroll to the bottom).

like image 106
Andrew Grimm Avatar answered Sep 29 '22 20:09

Andrew Grimm


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')) }
like image 44
Oscar Del Ben Avatar answered Sep 29 '22 19:09

Oscar Del Ben