繁体   English   中英

使用Ruby在具有特定字母的数组中查找对象

[英]Finding an object(s) within an array with specific letter using Ruby

因此,我试图创建一个将Array和一个字母作为参数并返回包含该字母的单词的新数组的方法。

到目前为止,我有:

def finder(array, thing_to_find)
  find = array.keep_if {|x| x.include?(thing_to_find)==true}
   return find
end

当我在Ruby中运行程序时,是说.include? 不是有效的阻止方法。

有什么建议么?

您可以编写更简单的方法-

def finder(array, thing_to_find)
  array.select { |word| word.include? thing_to_find }
end

在每次迭代中, array会将每个元素word从该array传递到块。 现在word.include?(thing_to_find)求值-如果返回true ,则将选择word并将其存储到临时数组中,否则不进行存储。 一旦完成关于该array所有迭代,然后将从每个块执行中选择的所有元素(存储在一个临时数组中)都将返回该数组。

暂无
暂无

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

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