How do I dynamically define a method as private?

后端 未结 3 875
刺人心
刺人心 2021-01-04 08:52

This does not seem to work:

class Test
  private

  define_method :private_method do 
    \"uh!\"
  end
end

puts Test.new.private_method
3条回答
  •  遥遥无期
    2021-01-04 09:36

    Module#private takes an optional argument for the method name:

    class Test
     private :private_method
    end
    

    The above is of course equivalent to

    Test.private :private_method # doesn't work
    

    Except that Module#private is private, so you have to use reflection to circumvent the access restrictions:

    Test.send :private, :private_method
    

    No eval necessary.

提交回复
热议问题