在数组中搜索 ruby 中的字符串及其子字符串

Search an array for a string and its substrings in ruby

我想在数组中搜索某个字符串和(!)它的子字符串。例如我的数组是:

array = ["hello", "hell", "goodbye", "he"]

所以当我搜索 "hello" 及其子字符串时(但仅从头开始:"he"、"hell"、"hello"),它应该 return

=> ["hello", "hell", "he"]

到目前为止我尝试了什么: 使用正则表达式和 #grep and/or #include?方法如下:

array.grep("hello"[/\w+/])

array.select {|i| i.include?("hello"[/\w+/])}

但在这两种情况下都只有 returns

=> ["hello"] 

顺便说一下,如果我尝试 array.select{|i| i.include?("he")} 它会起作用,但就像我说的那样我想要相反的方法:搜索 "hello" 并从头开始给我所有结果,包括子字符串。

使用array#keep_if

array = ["hello", "hell", he"]
substrings = array.keep_if{|a| a.start_with?('h')}
=> ["hello", "hell", "he"]
array = ["hello", "hell", "goodbye", "he", "he"]

# define search word:
search = "hello"

# find all substrings of this word:
substrings = (0..search.size - 1).each_with_object([]) { |i, subs| subs << search[0..i] }
#=> ["h", "he", "hel", "hell", "hello"]

# find intersection between array and substrings(will exclude duplicates):
p array & substrings
#=> ["hello", "hell", "he"]

# or select array elements that match any substring(will keep duplicates):
p array.select { |elem| substrings.include?(elem) }
#=> ["hello", "hell", "he", "he"]

hello中除h以外的字符全部设为可选

> array = ["hello", "hell", "goodbye", "he"]
> array.select{|i| i[/^he?l?l?o?/]}
=> ["hello", "hell", "he"]

您仍然可以像这样使用正则表达式

#define Array
arr = ["hello", "hell", "goodbye", "he"]
#define search term as an Array of it's characters
search = "hello".split(//)
#=> ['h','e','l','l','o']
#deem the first as manditory search.shift
#the rest are optional ['e?','l?','l?','o?'].join
search = search.shift << search.map{|a| "#{a}?"}.join
#=> "he?l?l?o?"
#start at the beginning of the string \A
arr.grep(/\A#{search}/)
#=> ["hello", "hell", "he"]

正如题中所写:

array.select { |w| "hello" =~ /^#{w}/ }
  #=> ["hello", "hell", "he"]
require "abbrev"

arr = ["hello", "hell", "goodbye", "he"]
p arr & ["hello"].abbrev.keys # => ["hello", "hell", "he"]

我会使用 String#[] :

array = ["hello", "hell", "goodbye", "he", "he"]
search = "hello"
array.select { |s| search[/\A#{s}/] }
# => ["hello", "hell", "he", "he"]