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/编码非常陌生。