From: Eric Christopherson Date: 2013-03-04T05:34:19+09:00 Subject: Re: How differs `Private` methods from `singleton methods`? On Sat, Mar 2, 2013 at 10:09 AM, D. Deryl Downey wrote: > Private methods are methods defined in a class that only instances of that > class can see and use. Not true in Ruby. In Ruby, a private method can only be called on self. And an explicit receiver (even if it is `self`) is not allowed, *unless* the method is a setter. E.g.: 1.9.3p194 :001 > class Foo 1.9.3p194 :002?> attr_accessor :bar 1.9.3p194 :003?> private :bar= 1.9.3p194 :004?> 1.9.3p194 :005 > def set_bar_private(obj) 1.9.3p194 :006?> self.bar = obj 1.9.3p194 :007?> end 1.9.3p194 :008?> private :set_bar_private 1.9.3p194 :009?> 1.9.3p194 :010 > def set_bar_public_using_accessor(obj) 1.9.3p194 :011?> self.bar = obj 1.9.3p194 :012?> end 1.9.3p194 :013?> 1.9.3p194 :014 > def set_bar_public_using_private_without_receiver(obj) 1.9.3p194 :015?> set_bar_private(obj) 1.9.3p194 :016?> end 1.9.3p194 :017?> 1.9.3p194 :018 > def set_bar_public_using_private_with_self_as_receiver(obj) 1.9.3p194 :019?> self.set_bar_private(obj) 1.9.3p194 :020?> end 1.9.3p194 :021?> end => nil 1.9.3p194 :022 > f = Foo.new => # 1.9.3p194 :023 > f.bar = 42 NoMethodError: private method `bar=' called for # from (irb):23 from /Users/eric/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `
' 1.9.3p194 :024 > f.set_bar_private 42 NoMethodError: private method `set_bar_private' called for # from (irb):24 from /Users/eric/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `
' 1.9.3p194 :025 > f.set_bar_public_using_accessor 42 => 42 1.9.3p194 :026 > f.bar => 42 1.9.3p194 :027 > f.set_bar_public_using_private_without_receiver 43 => 43 1.9.3p194 :028 > f.bar => 43 1.9.3p194 :029 > f.set_bar_public_using_private_with_self_as_receiver 44 NoMethodError: private method `set_bar_private' called for # from (irb):19:in `set_bar_public_using_private_with_self_as_receiver' from (irb):29 from /Users/eric/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `
' 1.9.3p194 :030 > > > Singleton methods are methods added on to an individual instance that > other instances of the same class will not have. Only THAT instance will > have that method. (You can even define a singleton on a class, but the > *instances* of that class won't have the singleton method added. It > applies to that class (which if you know ruby you know a class is also an > object in its own right) object only. > > > On 3/2/13 8:09 AM, "Kumar R." wrote: > >>Can anyone help me to understand the difference between `private >>methods` and `singleton methods` in Ruby? >> >>-- >>Posted via http://www.ruby-forum.com/. >> > > >