Optional arguments with default value in Ruby

后端 未结 3 1827
既然无缘
既然无缘 2020-12-10 19:13

I would like to create a function that has optional arguments with default values

def my_function(a = nil, b=nil, c=500)

end

and call the

3条回答
  •  被撕碎了的回忆
    2020-12-10 19:50

    So you're trying to implement keyword arguments? This is supposed to be a new feature in Ruby 2.0, but you can try to mimic it in 1.9.x with a hash of arguments instead. Here's a post that discusses how you can accomplish that, which gives the following code sample:

    def foo(options = {})
      options = {bar: 'bar'}.merge(options)
      puts "#{options[:bar]} #{options[:buz]}"
    end
    
    foo(buz: 'buz') # => 'bar buz'
    

提交回复
热议问题