是否有一种方法来检查方法的参数是由方法本身的默认值设置的,还是由调用该方法的用户设置的?
下面是我想在我的方法中做的事情,例如
def json_prop(key, value = nil)
json_data = {} if json_data.nil?
return json_data[key] if value.set_by_user? # i.e. User did not set value to nil himself
json_data[key] = value # Set to the value inserted by the user when calling the method
end发布于 2022-08-29 05:03:54
要做到这一点有一个标准技巧,它依赖Ruby编程语言的两个特性:
因此,我们所需要做的就是在默认的参数值表达式中设置一个变量,并且我们知道:如果设置了变量,则计算默认的参数值表达式,因此没有传递参数值:
def json_prop(key, value = (no_value_set_by_user = true; nil))
json_data = {} if json_data.nil?
return json_data[key] if no_value_set_by_user
json_data[key] = value
end或
def json_prop(key, value = (
no_value_set_by_user = true
nil
))
json_data = {} if json_data.nil?
return json_data[key] if no_value_set_by_user
json_data[key] = value
endhttps://stackoverflow.com/questions/73522549
复制相似问题