Understanding private methods in Ruby

前端 未结 7 1216
终归单人心
终归单人心 2020-11-29 00:01
class Example
 private
 def example_test
  puts \'Hello\'
 end
end

e = Example.new
e.example_test

This of course will not work, because we specifi

7条回答
  •  再見小時候
    2020-11-29 00:57

    Adding some enhancements to User Gates solution. Calling a private method to class method or an instance method is pretty much possible. Here is the Code Snippets. But not recommended.

    Class Method

    class Example
      def public_m
        Example.new.send(:private_m)
      end
    
      private
      def private_m
        puts 'Hello'
      end
    end
    
    e = Example.new.public_m
    

    Instance Method

    class Example
      def self.public_m
        Example.new.send(:private_m)
      end
    
      private
      def private_m
        puts 'Hello'
      end
    end
    
    e = Example.public_m
    

提交回复
热议问题