Rails optional argument

后端 未结 4 856
礼貌的吻别
礼貌的吻别 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:20

    It's as simple as this:

    class Person
        attr_accessor :name, :age
    
        def initialize(name = '', age = 0)
            self.name = name
            self.age = age
        end
    end
    
    
    Person.new('Ivan', 20)
    Person.new('Ivan')
    

    However, if you want to pass only age, the call would look pretty ugly, because you have to supply blank string for name anyway:

    Person.new('', 20)
    

    To avoid this, there's an idiomatic way in Ruby world: options parameter.

    class Person
        attr_accessor :name, :age
    
        def initialize(options = {})
            self.name = options[:name] || ''
            self.age = options[:age] || 0
        end
    end
    
    Person.new(name: 'Ivan', age: 20)
    Person.new(age: 20)
    Person.new(name: 'Ivan')
    

    You can put some required parameters first, and shove all the optional ones into options.

    Edit

    It seems that Ruby 2.0 will support real named arguments.

    def example(foo: 0, bar: 1, grill: "pork chops")
      puts "foo is #{foo}, bar is #{bar}, and grill is #{grill}"
    end
    
    # Note that -foo is omitted and -grill precedes -bar
    example(grill: "lamb kebab", bar: 3.14)
    

提交回复
热议问题