1

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.

2
  • Is the other_name == name || necessary? Would be a bit cleaner without it. Commented Mar 4, 2011 at 3:40
  • Yes, otherwise everything would be excluded, including "question". Commented Mar 4, 2011 at 17:37

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Yep, that is better. Appreciate the help.
That can be shortened even more using names.one? { |other_name| other_name[name] }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.