![](/img/trans.png)
[英]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.