Rails optional argument

后端 未结 4 840
礼貌的吻别
礼貌的吻别 2020-12-07 17:49

I have a class

class Person
    attr_accessor :name,:age
    def initialize(name,age)
        @name = name
        @age = age
    end
end

I

4条回答
  •  时光说笑
    2020-12-07 18:05

    This is more of a Ruby thing. You can define optional arguments for a method like this:

    def initialize(name="", age=0)
      @name = name
      @age = age
    end
    

    By doing it this way, you will be able to call Person.new and then have name default to a blank string if it's not passed and age default to 0. If you want age to be something but name to be blank you'll need to pass an empty string anyway:

    Person.new("", 24)
    

提交回复
热议问题