Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.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 - Fatal编程技术网

Ruby 块参数的默认值

Ruby 块参数的默认值,ruby,Ruby,我想创建一个方法,它接受一个块参数,但将块默认为一个总是返回true的方法 def my_method(&print_if = Proc.new { true }) internal_value = [1, 2, 3] puts "printing" if print_if.call(internal_value) end my_method { |array| array[1] == 2 } "printing" => nil my_method { |array|

我想创建一个方法,它接受一个块参数,但将块默认为一个总是返回true的方法

def my_method(&print_if = Proc.new { true })
  internal_value = [1, 2, 3]
  puts "printing" if print_if.call(internal_value)
end

my_method { |array| array[1] == 2 }
 "printing"
 => nil
my_method { |array| array[1] == 3 }
 => nil
my_method
 "printing"
 => nil
我的最佳选择似乎是检查方法中是否存在块。这样行得通,只是更笨重

def my_method(&print_if)
  internal_value = [1, 2, 3]
  puts "printing" if !block_given? || print_if.call(internal_value)
end

my_method { |array| array[1] == 2 }
 "printing"
 => nil
my_method { |array| array[1] == 3 }
 => nil
my_method
 "printing"
 => nil

有没有办法在Ruby中默认一个block arg?请不要回答依赖于外部库(甚至是Rails)的问题,只是想看看纯Ruby是否可以做到这一点。

您可以使用这个肮脏的黑客:

def my_method(print_if = -> (*args) { block_given? ? yield(*args) : true })
  internal_value = [1, 2, 3]
  puts "printing" if print_if.call(internal_value)
end

但是它方便吗?

你也可以(用你的第二个)示例
print_if | |=->{true}
我刚刚注意到你的第二个代码块,在发布我的答案后(自删除),但这一点没有错,因为代码完美地描述了你想要实现的目标。我个人认为
print\u if.nil?true:print_if.call(internal_value)
读起来更好。@Sergio,你在说什么?记住,将块声明为参数会带来相当大的性能损失,因为Ruby需要为能够传递的块捕获大量上下文信息。只要有可能,请结合使用
block\u给定?
yield
。对于光照使用,差异很大程度上是学术性的,但是对于性能敏感的代码,差异可能是巨大的。一般的规则是,如果需要将块转发到另一个方法,则只声明块参数,在这种情况下,无论如何都要付出代价。我认为这个答案非常好,因为它证明Ruby没有一种很好的方法来设置应为procs/lambdas/blocks的参数的默认值。我不是Ruby允许传递方法的最大粉丝,但这就是生活。我只是想看看我是否错过了一条捷径。