Controlling Access by Making Methods Private : private « Class « Ruby






Controlling Access by Making Methods Private


class MyNumber
  def initialize
    @secret = rand(20)
  end

  def hint
    puts "The number is #{"not " if secret <= 10}greater than 10."
  end

  private
  def secret
    @secret
  end
end

s = MyNumber.new
s.secret
s.hint

class OurNumber < MyNumber
  def hint
    lower = secret-rand(10)-1
    upper = secret+rand(10)+1
    "The number is somewhere between #{lower} and #{upper}."
  end
end

ls = OurNumber.new
ls.hint
# => "The number is somewhere between -3 and 16."
ls.hint
# => "The number is somewhere between -1 and 15."
ls.hint
# => "The number is somewhere between -2 and 16."

 








Related examples in the same category

1.When you make a method private, it's not accessible outside the object it's defined in