Private?

I’m trying to understand a ruby class,\

class Timer

  attr_accessor :seconds

  def initialize
    @seconds = 0
  end

  def time_string
    convert(@seconds)
    "#{padded(@hrs)}:#{padded(@min)}:#{padded(@sec)}"
  end

  private

  def padded(num)
    if num <= 9
      "0#{num}"
    else
      "#{num}"
    end
  end

  def convert(num)
    if num >= 3600
      @hrs = num / 3600
      @min = (num - (@hrs * 3600)) / 60
      @sec = num - (3600 + (@min * 60))
    elsif num < 3600 && num >= 60
      @hrs = 0
      @min = num / 60
      @sec = num - (@min * 60)
    else
      @hrs = 0
      @min = 0
      @sec = num
    end
  end
end

The only thing i dont understand is, what is the deal with private being in the middle?

Thank you!

Hi,

When posting code samples, could you please use code tags.
See here: http://www.sitepoint.com/forums/showthread.php?1041498-Proposed-Template-Sticky&p=5407985&viewfull=1#post5407985

To answer your question, when private is invoked without arguments, it sets access to private for all subsequent methods, meaning that they may only be accessed by methods of the same class.

E.g.

t = Timer.new
=&gt; #&lt;Timer:0x436668 @seconds=0&gt;

t .seconds = 100
=&gt; #&lt;Timer:0x436668 @seconds=100&gt;

t.time_string
=&gt; "00:01:40"

t.padded(100)
=&gt; timer.rb:46:in `<main>': private method `padded' called for #&lt;Timer:0x436668 @seconds=100, @hrs=0, @min=1, @sec=40&gt; (NoMethodError)

ok, thanks again, ya’know you Germans are a ok bunch (and smart)!

And when arguments are provided they are used to designate those methods that are to be private within the class.


class Timer
  
  private :padded, :convert

  attr_accessor :seconds
 
  def initialize
    @seconds = 0
  end
 
  def time_string
    convert(@seconds)
    "#{padded(@hrs)}:#{padded(@min)}:#{padded(@sec)}"
  end
  
  def padded(num)
    if num <= 9
      "0#{num}"
    else
      "#{num}"
    end
  end
 
  def convert(num)
    if num >= 3600
      @hrs = num / 3600
      @min = (num - (@hrs * 3600)) / 60
      @sec = num - (3600 + (@min * 60))
    elsif num < 3600 && num >= 60
      @hrs = 0
      @min = num / 60
      @sec = num - (@min * 60)
    else
      @hrs = 0
      @min = 0
      @sec = num
    end
  end
end

Thanks :slight_smile:
I’m afraid I’m British though (ex-pat).