A method with an optional parameter

怎甘沉沦 提交于 2019-12-17 11:31:22

问题


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?

some_func(variable)

some_func

回答1:


def some_func(variable = nil)
  ...
end



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/35747905/a-method-with-an-optional-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!