Binary Logic
Binary Logic

Reputation: 2592

Ruby: eliminate strings that are substrings of other strings in an array

I thought this would be an interesting question to post. I have a solution, I'm curious if there is a better way to do this. Say you have this array:

names = ["on", "question", "quest"]

I want to eliminate strings that are substrings of other members in the array. The cleanest code I could come up with is:

names.select do |name|
    names.all? { |other_name| other_name == name || other_name.match(name).nil? }
end

The result is

["question"]

I hate that code, just doesn't seem very ruby like. Any suggestions on a better / more efficient / more concise way to do this?

Thanks for the help.

Upvotes: 1

Views: 133

Answers (2)

rubyprince
rubyprince

Reputation: 17803

I have a little addition to make. Use include? method of string

names.select do |name|
  names.one? {|other_name| other_name.include? name}
end

Upvotes: 2

RameshVel
RameshVel

Reputation: 65887

Wouldn't this easier

names.select do |name|
      names.one? {|other_name|  other_name.index(name)!=nil}
end

It checks if the item is a part of any one of the item in array.

Upvotes: 1

Related Questions