0

I have the following array:

arr = ["lol","test"]

and a code:

matches = content.downcase.split & arr

where content is a string. This code returns ["lol"] when content = "Something lol", but fails to return anything when content = "Something #lol." with a comma or hashtag etc. It always fails when there is no exact match.

I'd like to match with the strings in the array as substring. How can this be done by adapting the above code?

1
  • Does "lol" in arr match "Something xlolx"? Commented Aug 15, 2015 at 14:54

4 Answers 4

1

Not efficient, but this works:

matches = content.downcase.split.select{|s| arr.any?{|_s| s.include?(_s)}}
Sign up to request clarification or add additional context in comments.

Comments

0

Try splitting on non-word boundary as shown below

arr = ["lol","test"]

content = "Something #lol."
p matches = content.downcase.split(/\W/) & arr

Outputs

["lol"]

Sample runs from Try ruby is shown below

enter image description here

2 Comments

What you mean it fails ? Can you please let me what you see? I updated my answer with output I see
simply does not match and returns empty
0

It's not obvious what kind of results you want to receive. I think you can use String#scan. It will return an array of matched data:

patterns = ["lol","test"]
data = content.downcase
matches = patterns.flat_map { |pattern| data.scan(pattern) }

Comments

0
s = content.downcase
arr.select { |w| s =~ /\b#{w}\b/ }

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.