ReWrite
ReWrite

Reputation: 2708

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

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?

Upvotes: 7

Views: 2193

Answers (2)

Wayne Conrad
Wayne Conrad

Reputation: 108199

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> 

Upvotes: 15

makevoid
makevoid

Reputation: 3297

use $0

in irb the value of $0 is "irb"

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

an explanation here

Upvotes: 5

Related Questions