gpt4 book ai didi

ruby - 如何编写 Ruby 方法来处理零个、一个或多个输入?

转载 作者:数据小太阳 更新时间:2023-10-29 07:29:39 24 4
gpt4 key购买 nike

我有一个如下所示的 Ruby 方法:

# Retrieve all fruits from basket that are of the specified kind.
def fruits_of_kind(kind)
basket.select { |f| f.fruit_type == kind.to_s }
end

现在,您可以这样调用它:

fruits_of_kind(:apple)    # => all apples in basket
fruits_of_kind('banana') # => all bananas in basket

等等。

如何更改方法,使其能够正确处理可迭代输入以及无输入和 nil 输入?例如,我希望能够支持:

fruits_of_kind(nil) # => nil
fruits_of_kind(:apple, :banana) # => all apples and bananas in basket
fruits_of_kind([:apple, 'banana']) # => likewise

这可以按照惯用方式进行吗?如果是这样,编写方法以接受零个、一个或多个输入的最佳方法是什么?

最佳答案

您需要使用 Ruby splat 运算符,它将所有剩余的参数包装到一个数组中并将它们传入:

def foo (a, b, *c)
#do stuff
end

foo(1, 2) # a = 1, b = 2, c = []
foo(1, 2, 3, 4, 5) #a = 1, b = 2, c = [3, 4, 5]

在你的情况下,这样的事情应该有效:

def fruits_of_kind(*kinds)
kinds.flatten!
basket.select do |fruit|
kinds.each do |kind|
break true if fruit.fruit_type == kind.to_s
end == true #if no match is found, each returns the whole array, so == true returns false
end
end

编辑

我更改了代码以扁平化种类,以便您可以发送列表。此代码将处理所有类型的输入,但如果您想明确输入 nil,请在开头添加行 kinds = [] if kinds.nil?

关于ruby - 如何编写 Ruby 方法来处理零个、一个或多个输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/840136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com