开发者

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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜