简体   繁体   English

Ruby:将`&proc`和`proc`传递给方法之间的区别

[英]Ruby: Difference between passing `&proc` and `proc` to a method

I have a bit of code modified slightly from a question on codeacademy. 我对codeacademy的问题做了一些修改。 The code is : 代码是:

def print_list(array, first = 1)
  counter = first
  array.each do |array|
    puts "#{yield counter} #{array}"
    counter = counter.next
  end
end

proc = Proc.new do |n|
  "[#{100*n}]:"
end

print_list ["alpha", "beta", "gamma"], 5, &proc

If I remove the & from the last line Ruby throws me an argument error. 如果我从最后一行删除&,Ruby会抛出参数错误。 What is the purpose of the & here? &这里的目的是什么?

If you remove the & , then print_list treats proc as a third argument to itself, instead of a block. 如果删除& ,则print_listproc视为自身的第三个参数,而不是块。 The & symbol transforms the Proc object into a block, which is called inside print_list by the yield keyword. &符号变换Proc对象成块,其被称为内部print_listyield关键字。

More succinctly, proc is just an argument, &proc is a reference to the block passed to the method. 更简洁地说, proc只是一个参数, &proc是对传递给该方法的块的引用。

You might find this article useful to understand the differences between proc and blocks 您可能会发现本文对理解proc和块之间的区别很有帮助

The & indicates that the proc should be passed as a block. &表示proc应该作为一个块传递。

Without it, the "proc" will just be another (third) parameter so you'll get the argument error (3 for 2) 没有它,“ proc”将只是另一个(第三个)参数,因此您将得到参数错误(3个代表2)

It's possible to pass it without the & and use it in your print_list method directly as a proc... but first can't be optional then. 可以在不带&的情况下传递它,并直接将它作为proc在您的print_list方法中使用...但是首先不能是可选的。 You'll need to pass first or at the very least nil. 您需要先通过,或者至少要通过。

def print_list(array, first, proc)
  counter = first || 1
  array.each do |array|
    puts "#{proc.call counter} #{array}"
    counter = counter.next
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM