Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 使用两个输入对数组中的字符串进行Grep_Arrays_Ruby_Grep - Fatal编程技术网

Arrays 使用两个输入对数组中的字符串进行Grep

Arrays 使用两个输入对数组中的字符串进行Grep,arrays,ruby,grep,Arrays,Ruby,Grep,我需要搜索一个数组,找出哪些对象包含特定的字符串。该方法必须有两个输入 这是一种单输入法,可以工作,并返回所有带有字母t的对象: def my_array_finding_method(source) source.grep(/t/) end my_array_finding_method(array) 这不起作用: def my_array_finding_method(source, thing_to_find) source.grep(/thing_to_find/) end

我需要搜索一个数组,找出哪些对象包含特定的字符串。该方法必须有两个输入

这是一种单输入法,可以工作,并返回所有带有字母
t
的对象:

def my_array_finding_method(source)
  source.grep(/t/)
end

my_array_finding_method(array)
这不起作用:

def my_array_finding_method(source, thing_to_find)
  source.grep(/thing_to_find/)
end

my_array_finding_method(array, "t")
我必须修改第二位代码才能工作。我如何才能这样做?

您必须输入变量名。否则,它将被解释为纯文本

source.grep(/#{thing_to_find}/)

您不必使用正则表达式:

def my_array_finding_method(source, thing_to_find)
  source.select { |s| s.include?(thing_to_find) }
end

arr = %w| It's true that cats have nine lives. |
   #=> ["It's", "true", "that", "cats", "have", "nine", "lives."] 
my_array_finding_method(array, "t")
   #=> ["It's", "true", "that", "cats"] 

非常感谢。这正是我所需要的,在将来会非常有帮助。因为这是我的第一个问题,也是一个非常基本的问题,我确信我对Ruby/编码非常陌生。