What's the point of an interactive Ruby subshell?
Asked Answered
C

1

5

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?

Comnenus answered 3/5, 2013 at 18:47 Comment(3)
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
T
9

So far I've seen three usefull things irb subsessions can do for you:

  1. undefine local variables
  2. change self of an irb session
  3. 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 subsession
  • jobs: list subsessions
  • fg: switch to a subsession
  • kill: kill a subsession

See this insteresting SO answer for details.

Tatterdemalion answered 3/5, 2013 at 18:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.