Reputation: 17234
I read this question but this doesn't answer it. Is there a ruby equivalent of "python -i"?
If my script is,
#!/usr/bin/ruby
hello = "Hello World"
If I use irb -r main.rb
, I get,
1.8.7 :001 > puts hello
NameError: undefined local variable or method `hello' for #<Object:0x7fb1486f4298>
from (irb):1
1.8.7 :002 >
It only works if I have hello defined as global. So, it's actually not "python -i"'s equivalent.
So, what's the exact equivalent?
Upvotes: 3
Views: 210
Reputation: 1666
So it turns out there is actually an evil hackish way of doing this:
ruby -rpry <(echo "$(cat main.rb)\nbinding.pry")
(requires pry
gem)
The <(
...)
is a Bash process substitution that effectively makes a pipe containing the result of evaluating the expression in parentheses that Ruby can then evaluate.
The echo "$(cat main.rb)\nbinding.pry"
outputs the contents of a file, in this case named main.rb
, and adds on a newline and the Ruby code binding.pry
, which, when combined with require
ing pry
with -rpry
enables Pry's runtime invocation that exposes the entire program's state to the interactive debugger.
(Using your main.rb
from above)
$ ruby -rpry <(echo "$(cat main.rb)\nbinding.pry")
From: /proc/self/fd/11 @ line 4 :
[1] pry(main)> puts hello
Hello World
=> nil
[2] pry(main)>
If the logic in your program relies on accessing any variables like _file_
or command-line arguments that are specific to running a file the correct way, it won't work. That being said, Dir.pwd
and require
ing seem to work normally, as long as you are executing the command from the same directory as the file.
Upvotes: 1
Reputation: 11736
According to Kernel#load documentation,
In no circumstance will any local variables in the loaded file be propagated to the loading environment.
If you don't like globals or constants, one way would be to wrap your data in a module such as: main.rb:
module Wtf
@hello= "world"
def self.hello; @hello end
end
$ irb -r main.rb
> Wtf.hello
> "world"
Upvotes: 5