0

I want to extract a list which doesn't contain(not exact match) a word which I have given. Example:

a = ["drop", "drop down", "forum", "drop down forum"]

b = ["drop", "drop down", "forum", "drop down forum", "data"]

Input string is str = "drop"

Output should be like: a = ["forum", "data"]

It is like a "LIKE" query in MySQL but I want to do it using ruby language. Please help to solve this.

2
  • 1
    Is there any reason your example data has two arrays? Why is the output of a ["forum", "data"]? Must array b be combined with array a somehow? Commented Oct 16, 2020 at 11:09
  • Your title doesn't convey what you are trying to do. I think you want something like, "How to extract strings from an array that that do not contain certain words". You don't need "Ruby" in the title because "ruby" is a tag (as it must be). You don't want rails as a tag because it is a pure-Ruby question. Moreover, the other tags won't help in searches, so I suggest that "ruby" be the only tag. Commented Oct 16, 2020 at 18:38

2 Answers 2

3

Ref reject!, Deletes every element of self for which the block evaluates to true.

list = ["drop", "drop down", "forum", "drop down forum"]
str = 'drop'
list.reject!{|item| item.include? str} # list = ["forum"]

Note :- include? is case sensitive for ex:- 'Drop down'.include? 'drop' will return false.

For case insensitive we can do something like following

list.reject!{|item| item.downcase.include? str.downcase}

For multiple list you can do following

list_one = ["drop", "drop down", "forum", "drop down forum"]
list_two = ["drop", "drop down", "forum", "drop down forum", "data"]
(list_one + list_two).uniq.reject{|item| item.downcase.include? str.downcase} # ["forum", "data"]
Sign up to request clarification or add additional context in comments.

3 Comments

It would help to use meaningful variable names, not a and aa. How about list and item?
Can't we extract it by comparing 2 arrays with given string(input) ? Updated the question.
What about list = ["drop", "droplet", "gumdrops"]? That's why @Sampat used a regex with word boundaries.
1
list1 = ["drop", "drop down", "forum", "drop down forum"]

list2 = ["drop", "drop down", "forum", "drop down forum", "data"]

result = (list1 | list2).reject{ |i| i.match(/\bdrop\b/i) }
=> ["forum", "data"]

Comments

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.