Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 是否可以同时为函数中的所有参数指定默认值?_Ruby_Function - Fatal编程技术网

Ruby 是否可以同时为函数中的所有参数指定默认值?

Ruby 是否可以同时为函数中的所有参数指定默认值?,ruby,function,Ruby,Function,如果我有这样一个函数: def foo(a="this", b="this", c="this") end 是否有一些选项可以同时为它们设置默认值?比如: def foo(DEFAULT="this", a, b, c) end 元编程局部变量 如果您试图创建可以重写的位置方法局部变量,那么可以使用当前方法使用一些元编程。例如: def foo a=nil, b=nil, c=nil %i[a b c].ma

如果我有这样一个函数:

def foo(a="this", b="this", c="this")
end
是否有一些选项可以同时为它们设置默认值?比如:

def foo(DEFAULT="this", a, b, c)
end
元编程局部变量 如果您试图创建可以重写的位置方法局部变量,那么可以使用当前方法使用一些元编程。例如:

def foo a=nil, b=nil, c=nil
  %i[a b c].map do |v|
    binding.local_variable_get(v) ||
    binding.local_variable_set(v, "this")
  end
  [a, b, c]
end
foo 1
#=> [1, "this", "this"]

foo 1, 2
#=> [1, 2, "this"]
这会做你想做的事。例如:

def foo a=nil, b=nil, c=nil
  %i[a b c].map do |v|
    binding.local_variable_get(v) ||
    binding.local_variable_set(v, "this")
  end
  [a, b, c]
end
foo 1
#=> [1, "this", "this"]

foo 1, 2
#=> [1, 2, "this"]
其他办法 其他方法可能包括使用选项哈希:

  • 在方法签名中使用
    hash.new(“this”)
    的选项哈希
  • 在方法主体内部定义的
  • 在读取选项哈希时使用返回默认值

如果你的目标只是干涸你的代码,最好考虑一下(例如,代码> DEFO**KWARGS ),而不是位置参数,但是你的里程可能会有所不同。

不清楚你想要什么。即使你想要的能起作用,这两个例子也不能做相同的事情。第一个示例创建三个不同的字符串,并将三个不同的对象作为三个不同参数的默认值,而第二个示例创建一个字符串,并将相同的字符串指定给所有三个参数。因此,如果方法的内容是
b.replace(“foo”);p a,b,c
,第一个会打印
这个foo这个
,第二个会打印
foo foo
。所以,完全不清楚你的目标是什么。