I have a bit of code modified slightly from a question on 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. 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. The &
symbol transforms the Proc
object into a block, which is called inside print_list
by the yield
keyword.
More succinctly, proc
is just an argument, &proc
is a reference to the block passed to the method.
You might find this article useful to understand the differences between proc and blocks
The & indicates that the proc should be passed as a block.
Without it, the "proc" will just be another (third) parameter so you'll get the argument error (3 for 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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.