Question

Considering this code:

def x; end
puts public_methods.include? :x

if I run it on irb and the ruby interpreter (both using Ruby 1.9.3) I get:

true # from irb
false # from ruby

Why are top-level methods defined publicly in irb and why does it differ from ruby?

irb session

Was it helpful?

Solution

I can confirm this behavior in Ruby 1.9.3p448.

I think it's because in irb's repl the definitions are wrapped in singleton, so to imitate it just put following in your script:

class << self
  def x; end
end

puts public_methods.member? :x    # true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top