OhDaeSu
OhDaeSu

Reputation: 525

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")} 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.

Upvotes: 2

Views: 2017

Answers (7)

Arup Rakshit
Arup Rakshit

Reputation: 118299

I'd use String#[] :

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

Upvotes: 2

steenslag
steenslag

Reputation: 80105

require "abbrev"

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

Upvotes: 3

Cary Swoveland
Cary Swoveland

Reputation: 110755

Just as the question reads:

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

Upvotes: 1

engineersmnky
engineersmnky

Reputation: 29598

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

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174874

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

Upvotes: 1

Rustam Gasanov
Rustam Gasanov

Reputation: 15791

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

Upvotes: 2

Darkmouse
Darkmouse

Reputation: 1939

Use array#keep_if

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

Upvotes: 0

Related Questions