0

I have the user input a string A for example "sun is clear". I have a string B in the database "sun cloud rain". How would I detect if part of String A is part of String B?

I used @sky.include?(activity.sky) where @sky is String A and activity.sky is String B. This works only when String A is sun.

3
  • do you mean that a word of String A a is a one of words of String B? Commented Dec 24, 2013 at 11:41
  • Yes, the condition should pass if one of the words from String A matches one of the words in String B. Commented Dec 24, 2013 at 11:42
  • For any strings A and B, a part of A is always a part of B. Proof: The empty string is part of A and is also a part of B. Commented Dec 24, 2013 at 11:56

4 Answers 4

4

You can split the strings into two arrays

a = "sun is clear".split
b = "sun cloud rain".split

and compute the intersection

a & b
# => ["sun"] 
(a & b).empty?
# => false

If the intersection is not empty, then they share pieces. Otherwise, you can also compute the difference of a - b

(a - b).size == a.size
# => false 
Sign up to request clarification or add additional context in comments.

3 Comments

This is a simple as (a & b).empty?
+1 Sets in Ruby make this sort of array work so clean.
very clean very easy to understand. Thankyou
1

To match a word of String A a is a one of words of String B use the following:

activity.sky.split( /\s+/ ).any? {|s| @sky.include?(s) }

Comments

0

split and then put & operator

(@sky.split(" ") & activity.sky.split(" ")).empty?

Comments

0

If neither A nor B itself includes a duplicate of words, then you can check like this:

A = "sun is clear"
B = "sun cloud rain"
"#{A} #{B}" =~ /\b(\w+)\b.*\b\1\b/ # => 0 (non-nil means there is a common word)

A = "sun is clear"
B = "cloud rain"
"#{A} #{B}" =~ /\b(\w+)\b.*\b\1\b/ # => nil (nil means there is no common word)

Otherwise, you can insert some non-letter non-space character (e.g., "|") between the two strings:

A = "sun is sun"
B = "sun cloud rain"
"#{A}|#{B}" =~ /\b(\w+)\b.*|.*\b\1\b/ # => 0

A = "sun is sun"
B = "cloud rain"
"#{A}|#{B}" =~ /\b(\w+)\b.*|.*\b\1\b/ # => nil

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.