如何编写Ruby方法来处理零个,一个或多个输入?
发布时间:2020-12-17 03:08:23 所属栏目:百科 来源:网络整理
导读:我有一个类似于以下的 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 bas
我有一个类似于以下的
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 等等. 如何更改方法以便正确处理可迭代输入以及无输入和零输入?例如,我希望能够支持: fruits_of_kind(nil) # => nil fruits_of_kind(:apple,:banana) # => all apples and bananas in basket fruits_of_kind([:apple,'banana']) # => likewise 这可能是惯用的吗?如果是这样,编写方法的最佳方法是什么,以便它们可以接受零个,一个或多个输入? 解决方法def fruits_of_kind(kind) return nil if kind.nil? result = [] ([] << kind).flatten.each{|k| result << basket.select{|f| f.fruit_type == k.to_s }} result end ‘splat’运算符可能是最好的方法,但有两点需要注意:传入nil或列表.要修改Pesto针对您想要的输入/输出的解决方案,您应该执行以下操作: def fruits_of_kind(*kinds) return nil if kinds.compact.empty? basket.select do |fruit| kinds.flatten.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,*将其转换为[nil].如果你想返回nil而不是空列表,你必须将它(删除空值)压缩为[],然后如果它为空则返回nil. 如果你传入一个列表,比如[:apple,’banana’],*将它转换为[[:apple,’banana’]].这是一个细微的差别,但它是一个包含另一个列表的单元素列表,因此您需要在执行“每个”循环之前展平各种类型.展平会将其转换为[:apple,就像您期望的那样,并为您提供您正在寻找的结果. 编辑:更好,感谢格雷格坎贝尔: def fruits_of_kind(basket,kind) return nil if kind.nil? kind_list = ([] << kind).flatten.map{|kind| kind.to_s} basket.select{|fruit| kind_list.include?(fruit) } end 或(使用splat) def fruits_of_kind(*kinds) return nil if kinds.compact.empty? kind_list = kinds.flatten.map{|kind| kind.to_s} basket.select{|fruit| kind_list.include?(fruit.fruit_type) } end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 1次ajax请求(XMLHttpRequest)上传多个文件,支持进度条
- AjAX Basic Example
- c – 如何有效地将cv :: Mat的给定通道设置为给定值而不改变
- c – 为什么我使用XCode的llvm和来自MacPorts的clang获得更
- c# – 在具有.aspx扩展名的mvc应用程序中获取Current.Reque
- c# – 抽象类没有任何抽象方法
- 数组索引循环变量在C,C中重置为零
- swift – 有没有理由为什么array [index]不返回可选项?
- ruby-on-rails – rails“public / system /”中rails“sys
- 07 ScrollView 滚动视图