Sunday, June 20, 2010

Executing private methods

To execute a private method simply delegate the call to method 'send' e.g.
class TicketSystem
  attr_reader :current_ticket
  
  def initialize()
    @current_ticket = 0
  end

  def make_purchase
    @current_ticket += 1
  end

  private

  def print_private_expenses
    puts 'private expenses now printing ...'
  end
end

ts = TicketSystem.new

ts.make_purchase
#=> 1

ts.current_ticket
#=> 1 

ts.print_private_expenses
#=> NoMethodError: private method `print_private_expenses' called for #

ts.send :print_private_expenses
#=> private expenses now printing ...

http://snippets.dzone.com/posts/show/11665

No comments: