[英]Ruby - How to write a method that accepts a proc with varying numbers of params?
I am writing an Array#map!
我正在写一个
Array#map!
method in Ruby that should accept a proc: Ruby 中的方法应该接受一个过程:
def map!(&blck)
(0..self.length-1).each do |i|
self[i] = blck.call(i)
end
self
end
This works fine if the proc accepts 1 parameter, but not if there are several (or if it accepts the character as opposed to the index).如果 proc 接受 1 个参数,则此方法可以正常工作,但如果有多个参数(或者如果它接受字符而不是索引)则不行。 Two proc examples:
两个过程示例:
prc1 = Proc.new do |ch|
if ch == 'e'
'3'
elsif ch == 'a'
'4'
else
ch
end
end
and和
prc2 = Proc.new do |ch, i|
if i.even?
ch.upcase
else
ch.downcase
end
end
Is there a way to do this?有没有办法做到这一点?
You can always find out how many arguments that Proc takes:您总是可以找出 Proc 占用了多少 arguments:
def map!(&block)
case block.arity
when 1
# Takes 1 argument
when 2
# Takes 2 arguments
else
# etc.
end
end
This is a common pattern if you need to handle different argument counts in a particular way.如果您需要以特定方式处理不同的参数计数,这是一种常见的模式。
It's worth noting that unless you need to shuffle up the order of the arguments passed in you can always pass in too many and the excess will be ignored:值得注意的是,除非您需要将传入的 arguments 的顺序打乱,否则您总是可以传入太多,多余的将被忽略:
def example(&block)
block.call(1,2,3)
end
example { |v| p v }
# => 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.