A method with an optional parameter

后端 未结 3 1581
夕颜
夕颜 2020-12-03 09:16

Is there a way to make a method that can accept a parameter, but can also be called without one, in which case the parameter is regarded nil like the following?

3条回答
  •  一生所求
    2020-12-03 10:11

    You can also use a hash as argument and have more freedom:

    def print_arg(args = {})
      if args.has_key?(:age)
        puts args[:age]
      end
    end
    
    print_arg 
    # => 
    print_arg(age: 35, weight: 90)
    # => 35
    

提交回复
热议问题