简体   繁体   中英

Search an array for a string and its substrings in ruby

I want to search an array for a certain string and(!) its substrings. For example my array is:

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

So when I search for "hello" and its substrings (but only from the beginning: "he", "hell", "hello"), it should return

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

What I've tried so far: Using a regular expression with the #grep and/or the #include? method like this:

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

or

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

but in both cases it only returns

=> ["hello"] 

By the way, if I try array.select{|i| i.include?("he")} array.select{|i| i.include?("he")} it works but like I said I want it the other way around: searching for "hello" and give me all results including the substrings from the beginning.

require "abbrev"

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

I'd use String#[] :

array = ["hello", "hell", "goodbye", "he", "he"]
search = "hello"
array.select { |s| search[/\A#{s}/] }
# => ["hello", "hell", "he", "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"]

Turn all the characters other than h in hello to optional.

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

You could still use a regular expression like this

#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"]

Just as the question reads:

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

Use array#keep_if

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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