类与实例

时间:2017-02-23 13:57:21

标签: ruby

我正在尝试解决https://www.hackerrank.com/challenges/30-class-vs-instance但我收到了错误。 我的代码仅在intialAge小于0时有效。

* solution.rb:13:in amIOld': undefined method<' for nil:NilClass(NoMethodError)

class Person
  attr_accessor :age
  def initialize(initialAge)
    if initialAge < 0
        puts "Age is not valid, setting age to 0."
        age = 0
    else
        initialAge = age
    end
    age
  end
  def amIOld()
    if age < 13 
        puts "You are young."
    elsif age.between?(13, 18)
        puts "You are a teenager."
    else 
        puts "You are old."
    end
  end
  def yearPasses()
    age += 1
  end
end

1 个答案:

答案 0 :(得分:0)

答案是:

class Person attr_accessor :age def initialize(initialAge) @age = 0 if initialAge < 0 puts "Age is not valid, setting age to 0." @age = 0 else @age = initialAge end end def amIOld() if @age < 13 puts "You are young." elsif @age.between?(12, 17) puts "You are a teenager." else puts "You are old." end end def yearPasses() @age += 1 end end