Starting up an interactive Ruby shell in the Terminal ('irb'), one can continue to open up irb subshells endlessly. What's the point of this?
What's the point of an interactive Ruby subshell?
why shouldn't you be able to? –
Palestra
How about the need to try something without contamination of previously defined variables or classes, without opening a new terminal window and starting IRB there? –
Urinalysis
@theTinMan actually, classes continue to be defined in the irb subshell (just like modules). when defined in the subshell, they are avaiable even after closing the subshell. –
Tatterdemalion
So far I've seen three usefull things irb subsessions can do for you:
- undefine local variables
- change
self
of an irb session irb
is a part of a great set of tools
undefine local variables
The nested irb
starts a new subsession in which all local variables (not classes, modules etc.) are not defined any more.
irb(main):001:0> a = 1
#=> 1
irb(main):002:0> irb
irb#1(main):001:0> a
NameError: undefined local variable or method `a' for main:Object from (irb#1):1
change self
for an irb session
irb(main):001:0> self
#=> main
irb(main):002:0> irb "Hello World"
irb#1(Hello World):001:0> self
#=> "Hello World"
irb#1(Hello World):002:0> length
#=> 11
Note: This is also known as "change binding" of an irb session.
By the way: It's possible to change the binding without opening a subsession (cb
, irb_change-binding
both do that for you). But it's more convenient to get back to the old binding with subsession.
The best thing is, that irb
is just one of a useful set of commands
irb
: start a new subsessionjobs
: list subsessionsfg
: switch to a subsessionkill
: kill a subsession
See this insteresting SO answer for details.
© 2022 - 2024 — McMap. All rights reserved.