简体   繁体   English

如何将 (2-∞) 参数传递给 ruby​​ 方法?

[英]How do I pass (2-∞) arguments to a ruby method?

I'm working on a very simple exercise: a method that can multiply between two and an indefinite number of floats.我正在做一个非常简单的练习:一种可以在两个和无限数量的浮点数之间相乘的方法。 My first idea for doing this was to use the splat operator:我这样做的第一个想法是使用 splat 运算符:

def multiply a, b, *rest
  a * b * rest
end

That was unsuccessful.那是不成功的。 I then tried this:然后我尝试了这个:

def multiply *numbers
  total = 1
  numbers.each do |x|
   total = total * x 
  end
  total
end

The above is almost successful—the problem is that it will accept a single argument, and I want it to require at least two.以上几乎是成功的——问题是它会接受一个参数,我希望它至少需要两个。 How can I achieve this?我怎样才能做到这一点?

There are many options.有很多选择。 The one the author of the exercise probably intended for you to use is inject :该练习的作者可能打算供您使用的一个是inject

def multiply(*numbers)
  numbers.inject(&:*)
end

This will cause the same problem as your second implementation of multiply in that it will accept 0 or 1 arguments.这将导致与您的第二个multiply实现相同的问题,因为它将接受 0 或 1 个参数。 You can fix this by simply raising an ArgumentError if you don't have at least two:如果您没有至少两个,则可以通过简单地引发ArgumentError来解决此问题:

def multiply(*numbers)
  raise ArgumentError unless numbers.length >= 2
  numbers.inject(&:*)
end

You can go the other way and accept two actual arguments and splat the rest, and simply build the complete array you intend to multiply together:你可以反其道而行之,接受两个实际参数,然后将其余的参数分开,然后简单地构建你打算相乘的完整数组:

def multiply(a, b, *rest)
  [a, b, *rest].inject(&:*)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM