简体   繁体   English

Ruby - 如何编写一个接受具有不同数量参数的过程的方法?

[英]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.

相关问题 给定嵌套长度不同的嵌套数组在Ruby中共享一个元素,如何合并它们? - How to merge nested arrays of varying lengths, given they share an element in Ruby? 如何将数组转换为方法的参数? - How to Convert Array to Params of Method? 如何在Ruby中编写“if in”语句 - How to write an “if in” statement in Ruby 如何在数组中使用C编程显示十进制长度不同的多个数字? - How to display multiple numbers with varying decimal lengths in array, C programming? 编写一个 function “giveMeRandom”,它接受一个数字 n 并返回一个包含 n 个介于 0 和 10 之间的随机数的数组 - Write a function “giveMeRandom” which accepts a number n and returns an array containing n random numbers between 0 and 10 如何用Ruby中的数组对数字求和? - How to sum numbers with arrays in Ruby? 如何在Ruby中对数字数组求和? - How to sum array of numbers in Ruby? 我想要一个接受数组,低数字,高数字的方法。 并返回一个只包含数字的数组 - I want a method that accepts an array, low number, high number. and returns an array with only numbers in between that 创建一个接受数字数组的函数 - Creating a function that accepts an array of numbers 如何在二维数组上调用接受数组作为其参数的方法? - How to call a method that accepts arrays as its parameter on a 2D array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM