Why Module.methods () and reply_to? works differently in irb than in script?

I try to use reflective methods in Ruby and come across behavior that I find in reality.

The following examples seem to work differently in IRB and when ruby ​​script is called:

Example 1:

def myfun; end
p respond_to?(:myfun)

In IRb this says "true", In the script: "false".

Example 2:

ml = methods
def myfun; end
p methods - ml

In IRb, this says [: myfun]. In the script: [].

I found this under 1.8, 1.9 MRI, JRuby 1.5.6 etc., so I assume this is normal.

Why is the difference?

I was sure that the "answer"? this is a way to see if a method is available - why doesn't this work in the above case?

+5
source share
1 answer

- "" - private ruby ​​script. :

ml = private_methods
def myfun; end
p private_methods - ml #=> [:myfun]
p respond_to?(:myfun, true) #=> true

, :

self.myfun
# NoMethodError: private method ‘myfun’ called for main:Object

, IRB . :

class Object
  def irb_binding
    # this is where your entered code is evaluated
    def myfun; :ok; end # you can define methods in other methods
    self.myfun # and they are public by default
  end
end

p irb_binding # :ok

IRB , , :

require "irb"
foo = :ok
IRB.start
#>> foo
# NameError: undefined local variable or method `foo' for main:Object

, , , - , . .

+5

All Articles