gpt4 book ai didi

ruby - 检查是否没有参数传递

转载 作者:数据小太阳 更新时间:2023-10-29 07:02:36 26 4
gpt4 key购买 nike

这是一些代码:

$ cat 1.rb
#!/usr/bin/env ruby
def f p1 = nil
unless p1 # TODO
puts 'no parameters passed'
end
end
f
f nil
$ ./1.rb
no parameters passed
no parameters passed

问题是,有没有办法区分没有参数和传递了一个nil参数?

UPD

我决定在 javascript 中添加一个用例,希望让事情变得更清楚:

someProp: function(value) {
if (arguments.length) {
this._someProp = value;
}
return this._someProp;
}

最佳答案

一般使用有3种方式。一种方法是使用默认值设置另一个变量,指示是否评估默认值:

def f(p1 = (no_argument_passed = true; nil))
'no arguments passed' if no_argument_passed
end

f # => 'no arguments passed'
f(nil) # => nil

第二种方法是使用一些只在方法内部已知的对象作为默认值,这样外人就不可能将那个对象传入:

-> {
undefined = BasicObject.new
define_method(:f) do |p1 = undefined|
'no arguments passed' if undefined.equal?(p1)
end
}.()

f # => 'no arguments passed'
f(nil) # => nil

在这两个中,第一个更为地道。第二个(实际上是它的变体)在 Rubinius 中使用,但我从未在其他任何地方遇到过。

第三种解决方案是使用 splat 获取可变数量的参数:

def f(*ps)
num_args = ps.size
raise ArgumentError, "wrong number of arguments (#{num_args} for 0..1)" if num_args > 1
'no arguments passed' if num_args.zero?
end

f # => 'no arguments passed'
f(nil) # => nil

请注意,这需要您手动重新实现 Ruby 的偶数检查。 (而且我们仍然没有做对,因为这会在方法内部引发异常,而 Ruby 会在调用点引发异常。)它还要求您手动记录您的方法签名,因为自动文档生成器(如 RDoc 或 YARD)将推断出任意数量的参数,而不是单个可选参数。

关于ruby - 检查是否没有参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23765914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com