Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top