1

I am at the very beginning of learning Ruby. Following the instructions of the assignment I am working on, I need to create a ruby file variables.rb. I wonder if there is a way to do that from the level of irb?

I know that I can do that easily from the level of the terminal via:

touch variables.rb.

Is there a way to do it from the level of irb?

ajmpawlik
  • 13
  • 3
  • Compare https://stackoverflow.com/questions/6149850/how-to-run-a-rb-file-from-irb – matt May 09 '19 at 12:25
  • 3
    But my question would be: why? Just open another terminal window and do it from the shell, or do it with a text editor app. File manipulation in ruby itself is advanced stuff. – matt May 09 '19 at 12:27
  • You can suspend irb via Ctrl-Z, create the file via `touch ...`, and run `fg` to resume irb. – Stefan May 09 '19 at 12:29
  • @matt - it seemed like an important possible time optimization considering that I will be running ruby files form irb, and creating files seems like something that happens quite often. At the beginning of the learning process is quite difficult to understand what is really important. Back to the basic stuff now. – ajmpawlik May 09 '19 at 12:45

2 Answers2

3

Using File class

File.new("variables.rb", "w")

or you can run the same touch command in irb

`touch variables.rb`
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • I tried both and none of them works. When I write touch foo.txt I get: 2.2.3 :001 > touch foo.txt NameError: undefined local variable or method `foo' for main:Object from (irb):1 from /Users/Aleksandra/.rvm/rubies/ruby-2.2.3/bin/irb:11:in `
    '
    – ajmpawlik May 09 '19 at 12:29
  • I tried both and both work :) For the second one you need the two ` for real. It's the way ruby knows to run that in a subshell – Ursus May 09 '19 at 12:32
  • Note that `File.new(...)` returns the opened file object. Pass an empty block to have it closed afterwards. – Stefan May 09 '19 at 12:39
1

This will do the trick:

File.open("newfilename", "w") { |file| file.puts "your text" }

You can also use .write or .print, if you don't want the line break

AJ8
  • 41
  • 1
  • 4