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?
Asked
Active
Viewed 352 times
5
-
3why shouldn't you be able to? – Kevin May 03 '13 at 18:52
-
2How about the need to try something without contamination of previously defined variables or classes, without opening a new terminal window and starting IRB there? – the Tin Man May 03 '13 at 20:15
-
1@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. – tessi May 03 '13 at 21:00
1 Answers
9
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.