How can I create ruby file from irb?
Using File
class
File.new("variables.rb", "w")
or you can run the same touch
command in irb
`touch variables.rb`
Execute program file with irb and remain interactive
One way to do this is to use pry
and add the line binding.pry
at the point in your script where you want to bail out into the repl.
x = 3
puts "Hello!"
binding.pry
Then you can run your script with pry and it'll let you examine what's going on.
~> pry d.rb
Hello
[1] pry(main)> x
=> 3
[2] pry(main)>
How would I have irb require the config/boot.rb file from the directory I run irb in?
I would do:
config_file = File.join(Dir.pwd, 'config', 'boot.rb')
require config_file if File.exist?(config_file)
Can you 'require' ruby file in irb session, automatically, on every command?
I usually create a simple function like this:
def reload
load 'myscript.rb'
# Load any other necessary files here ...
end
With that, a simple reload
will re-import all of the scripts that I'm working on. It's not automatic, but it's the closest thing that I've been able to come up with.
You may be able to override method_missing
to call this function automatically when your object is invoked with a method that doesn't exist. I've never tried it myself, though, so I can't give any specific advice. It also wouldn't help if you're calling a method that already exists but has simply been modified.
In my own laziness, I've gone as far as mapping one of the programmable buttons on my mouse to the key sequence "reload<enter>". When I'm using irb
, all it takes is the twitch of a pinky finger to reload everything. Consequently when I'm not using irb
, I end up with the string "reload" inserted in documents unintentionally (but that's a different problem entirely).
How to load a ruby file in to IRB?
From the require
docs:
Any constants or globals within the loaded source file will be available in the calling program’s global namespace. However, local variables will not be propagated to the loading environment.
So if in options.rb
you have something like:
key = something
(i.e. key
is a local in the file) then it will not be available in irb. If you make it a global (e.g. $key = 'something'
) or a constant (e.g. KEY = 'something'
) it should be available.
Related Topics
Which Ruby Version am I Really Running
Ruby Timeouts and System Commands
Ruby: Split String at Character, Counting from the Right Side
Setter Method (Assignment) with Multiple Arguments
Problem with Quantifiers and Look-Behind
How to Find Each Instance of a Class in Ruby
Creating Permutations from a Multi-Dimensional Array in Ruby
Converting from Xml Name-Values into Simple Hash
Net::Ssh Sudo Command Hangs After Entering Password
Railstutorial - Chapter 8.4.3 - Test Database Not Clearing After Adding User in Integration Test
Render Three Different Partials Depending on Button Clicked
When (If) to Consolidate Activerecord Migrations
Homebrew Installation on MAC Os X Failed to Connect to Raw.Githubusercontent.Com Port 443