How can a Ruby script detect that it is running in irb?
Asked Answered
D

2

7

I have a Ruby script that defines a class. I would like the script to execute the statement

BoolParser.generate :file_base=>'bool_parser'

only when the script is invoked as an executable, not when it is require'd from irb (or passed on the command line via -r). What can I wrap around the statement above to prevent it from executing whenever my Ruby file is loaded?

Dublin answered 9/2, 2010 at 5:34 Comment(0)
A
15

The condition $0 == __FILE__ ...

!/usr/bin/ruby1.8

class BoolParser

  def self.generate(args)
    p ['BoolParser.generate', args]
  end

end

if $0 == __FILE__
  BoolParser.generate(:file_base=>__FILE__)
end

... is true when the script is run from the command line...

$ /tmp/foo.rb
["BoolParser.generate", {:file_base=>"/tmp/foo.rb"}]

... but false when the file is required or loaded by another ruby script.

$ irb1.8
irb(main):001:0> require '/tmp/foo'
=> true
irb(main):002:0> 
Agripinaagrippa answered 9/2, 2010 at 6:6 Comment(0)
W
5

use $0

in irb the value of $0 is "irb"

in your file is "/path/to/file"

an explanation here

Warner answered 9/2, 2010 at 5:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.