IRb: how to start an interactive ruby session with pre-loaded classes

折月煮酒 提交于 2019-11-30 09:50:28

I'm not sure it's possible to 'flush' a session. However, you can load your classes like this:

irb -r 'hello.rb' -r 'hello_objects.rb'

You can manage sessions in irb. Start irb and try this:

x=1
irb     # Opens a new session
puts x  # error
jobs    # lists sessions
quit    # kills current session
puts x  # 1

There is also the command "fg (number)" which switches between sessions. See: http://tagaholic.me/2009/05/11/demystifying-irb-commands.html

I believe what you're looking for is modifying your ~/.irbrc file. It was mentioned earlier, but no examples given. Here is a short example of requiring some common utilities you may want in your irb session:

# Print to yaml format with "y"
require 'yaml'
# Pretty printing
require 'pp'
# Ability to load rubygem modules
require 'rubygems'
# Tab completion
require 'irb/completion'

You can put any ruby code into your ~/.irbrc file, which will get evaluated whenever you run irb. In this case your require statements.

These are not direct answers but can apply to your desire to understand irb more.

A number of "irb" methods are available to the console object.

methods.grep(/irb/).sort
=> ["irb", "irb_bindings", "irb_cb", "irb_change_binding", "irb_change_workspace",
"irb_chws", "irb_context", "irb_current_working_binding", "irb_current_working_workspace",
"irb_cwb", "irb_cws", "irb_cwws", "irb_exit", "irb_fg", "irb_jobs", "irb_kill", "irb_load",
"irb_pop_binding", "irb_pop_workspace", "irb_popb", "irb_popws", "irb_print_working_binding",
"irb_print_working_workspace", "irb_push_binding", "irb_push_workspace", "irb_pushb",
"irb_pushws", "irb_pwb", "irb_pwws", "irb_quit", "irb_require", "irb_source", "irb_workspaces"]

Have some fun playing around with those.

Another is the "conf" object that gives feedback about your irb environment:

conf
=> conf.ap_name="irb"
conf.auto_indent_mode=false
conf.back_trace_limit=16
conf.debug_level=1
conf.echo=true
conf.ignore_eof=false
conf.ignore_sigint=true
conf.inspect_mode=nil
conf.io=#<IRB::StdioInputMethod:0x79da0>
conf.irb=#<IRB::Irb:0x7c58c>
conf.irb_name="irb"
conf.irb_path="(irb)"
conf.last_value=...
conf.line_no=6
conf.load_modules=[]
conf.prompt_c="%N(%m):%03n:%i* "
conf.prompt_i="%N(%m):%03n:%i> "
conf.prompt_mode=:DEFAULT
conf.prompt_s="%N(%m):%03n:%i%l "
conf.rc=true
conf.return_format="=> %s\n"
conf.thread=#<Thread:0x31790 run>
conf.use_readline=false
conf.verbose=nil
conf.workspace=#<IRB::WorkSpace:0x7aa84 @main=main, @binding=#<Binding:0x7a2a0>>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!