A method with an optional parameter

后端 未结 3 1590
夕颜
夕颜 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:16

    Besides the more obvious option of parameters with default values, that Sawa has already shown, using arrays or hashes might be handy in some cases. Both solutions preserve nil as a an argument.

    1. Receive as array:

    def some_func(*args)
      puts args.count
    end
    
    some_func("x", nil)
    # 2
    

    2. Send and receive as hash:

    def some_func(**args)
      puts args.count
    end
    
    some_func(a: "x", b: nil)
    # 2
    

提交回复
热议问题