[英]How to merge nested arrays of varying lengths, given they share an element in Ruby?
[英]Ruby - How to write a method that accepts a proc with varying numbers of params?
我正在写一个Array#map!
Ruby 中的方法应该接受一个过程:
def map!(&blck)
(0..self.length-1).each do |i|
self[i] = blck.call(i)
end
self
end
如果 proc 接受 1 个参数,则此方法可以正常工作,但如果有多个参数(或者如果它接受字符而不是索引)则不行。 两个过程示例:
prc1 = Proc.new do |ch|
if ch == 'e'
'3'
elsif ch == 'a'
'4'
else
ch
end
end
和
prc2 = Proc.new do |ch, i|
if i.even?
ch.upcase
else
ch.downcase
end
end
有没有办法做到这一点?
您总是可以找出 Proc 占用了多少 arguments:
def map!(&block)
case block.arity
when 1
# Takes 1 argument
when 2
# Takes 2 arguments
else
# etc.
end
end
如果您需要以特定方式处理不同的参数计数,这是一种常见的模式。
值得注意的是,除非您需要将传入的 arguments 的顺序打乱,否则您总是可以传入太多,多余的将被忽略:
def example(&block)
block.call(1,2,3)
end
example { |v| p v }
# => 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.