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?
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
=> #<Timer:0x436668 @seconds=0>
t .seconds = 100
=> #<Timer:0x436668 @seconds=100>
t.time_string
=> "00:01:40"
t.padded(100)
=> timer.rb:46:in `<main>': private method `padded' called for #<Timer:0x436668 @seconds=100, @hrs=0, @min=1, @sec=40> (NoMethodError)
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