On 12 Aug 2010, at 01:12, David Waller wrote:

> Howdy from a Ruby newbie--hope my question isn't too annoying.
> 
> I'm working through a book on Ruby.  Examples using self work fine in
> irb, but if I type the same examples in a script and run that I get this
> error message: private method called for...NoMethodError.
> 
> So, my question is:  what do I need to type to properly invoke self in a
> script (but that is not needed in the irb?).
> 
> I should mention that the explanation of public vs. private methods
> isn't helping me.  If I could just see what I have to actually type to
> use self in a script vs. the irb a light would go off in my head.
> 
> Here's an example that runs in irb, but not in a script:
> 
> 
> def add(n)
>  self + n
> end
> 
> 
> puts 2.add(2)
> 
> 
> The irb will display the result 4, but the script gives the "private
> method...NoMethodError" message.
> 
> I'm puzzled as to why Ullman does not address this in his section on
> "Using Self."
> 
> Thanks!
> 
> -Doc Waller
> -- 
> Posted via http://www.ruby-forum.com/.

My irb gave me an error until I added the definition to a class (Integer seemed right) :

$ irb  
> 2.add(2)
NoMethodError: undefined method `add' for 2:Fixnum
	from (irb):1
	from /Library/Frameworks/Ruby.framework/Programs/irb:12:in `<main>'
> def add(n)
     self + n
    end
=> nil
> 2.add(2)
NoMethodError: private method `add' called for 2:Fixnum
	from (irb):5
	from /Library/Frameworks/Ruby.framework/Programs/irb:12:in `<main>'
> class Integer
    def add(n)
       self + n
      end
    end
=> nil
> 2.add(2)
=> 4

I'm not sure why your irb didn't give an error. Did you load any files into it?


Iain