ruby on rails - How to judge whether a method has defined in a class? -


  Class C1 until method_defined? : Hello # Surely, this is not right. I'm asking to find something to do this job.  

So, how to decide whether a method is defined or not?

Div class = "post-text" itemprop = "text">

You Posted by code method has been fixed or not It's OK to check it out. Is really the right choice (including variants, and so on.) The problem is def_method with your call, which does not exist. (It is called).

It works like a charm:

  Class C1 define_method (: Hello) Does finish "Hi everybody" until method_defined? Hi-end  

However, since you already know the name before and nobody do not stop, Module # Pribhashit_mthapn of no use There is no need, you instead only def can use keywords:

  class C1 def hello say 'Hi everybody "unless method_defined? : Hello and  

Or have I misunderstood your question and are you worried about heritage? In that case, the module # method_defined? is not the right choice, because it completely Heritage series runs in that case, you'll need to use it or take her cousin, or that an alternative argument, which Suprcls them / Micsin or involved in some way The ways to do must be included. (Note that the documentation is incorrect: If you have no argument, will will contain all legacy systems.)

  Class C1 until Instance_methods ( False) .include? Hello Deaf Hello "Hi all Android and and ' 

Here's a little test suite that states that my suggestion works:

  require 'Test / unit' class test defining method results & lt; Test :: Unit :: Test Seas Diif setup @ C1 = Clasknu Diif self.add_hello (which) define_method (: Hello) are timed to define what method? Hello finally end @o = @ end c1.new def test_that_the_method_doesnt_exist_when_it_hasnt_been_defined_yet loud !@c1.method_defined? (: Hello)! @ C1.instance_methods.include emphasis? (: नमस्ते) !@o.methods.include emphasis (: नमस्कार) by emphasizing !@o.respond_to? (Hello) assert_raise (NoMethodError) {@ o.hello} end def test_that_the_method_does_exist_after_it_has_been_defined @ c1.add_hello 'A' assert @ c1.method_defined? (Hello) assert @ c1.instance_methods.include? (: Hello) @ o.methods.include loud? (Hi) @o assert_respond_to ,: Hello assert_nothing_raised {@ o.hello} assert_equal 'a', @ end def test_that_the_method_cannot_be_redefined @ c1.add_hello 'emphasis on a' o.hello @ c1.method_defined? (: Hello) loud @ c1.instance_methods.include? (: Hello) loud @ o.methods.include? (Hi) @o assert_respond_to ,: Hello assert_nothing_raised {@ o.hello} assert_equal 'a', @ Oholo @ c1.add_hello 'two', @o assert_respond_to: Loud @ o.methods.include loud @ c1.method_defined? (: Hello) loud @ c1.instance_methods.include? (Hello)? (Hi): Hello assert_nothing_raised {@ o.hello} assert_equal 'should respond with an' @ o.hello, 'it * still * "A"! 'End and  

Comments