Understanding private methods in Ruby

前端 未结 7 1189
终归单人心
终归单人心 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 01:07

    Sorry for my prevoius answer. I just don't understand your question.

    I changed your code like this:

    class Foo
     def public_m
      private_m # <=
     end
    
     def Foo.static_m
       puts "static"
     end
    
     def self.static2_m
       puts "static 2"
     end
    
     private 
     def private_m
      puts 'Hello'
     end
    end
    
    Foo.new.public_m
    Foo.static_m
    Foo.static2_m
    

    Here is a call of instance method:

     def public_m
      private_m # <=
     end
    

    Here are a call of class methods:

     def Foo.static_m
       puts "static"
     end
    
     def self.static2_m
       puts "static 2"
     end
    
    Foo.static_m
    Foo.static2_m
    
    0 讨论(0)
提交回复
热议问题