0

I am attempting to search through an array of strings (new_string) and check if it includes any 'operators'

where am I going wrong?

def example
  operators = ["+", "-"]
  string = "+ hi"
  new_string = string.split(" ")
  if new_string.include? Regexp.union(operators)
    print "true"
  else
    print "false"
  end
end
1
  • You are asking whether an array of strings contains a specific regexp. Obviously, that will always be false, because your array doesn't contain regexps, it contains strings. Commented Dec 8, 2020 at 15:06

2 Answers 2

1

You can use any? instead, which takes a pattern:

pattern = Regexp.union(['+', '-']) #=> /\+|\-/

['foo', '+', 'bar'].any?(pattern) #=> true

But since you already have a string, you can skip the splitting and use match?:

'foo + bar'.match?(pattern) #=> true
Sign up to request clarification or add additional context in comments.

Comments

0

You wish to determine if a string (string) contains at least one character in a given array of characters (operators). The fact that those characters are '+' and '-' is not relevant; the same methods would be used for any array of characters. There are many ways to do that. @Stefan gives one. Here are a few more. None of them mutate (modify) string.

string = "There is a + in this string"
operators = ["+", "-"]

The following is used in some calculations.

op_str = operators.join
  #=> "+-"

#1

r = /[#{ op_str }]/
  #=> /[+-]/ 
string.match?(r)
  #=> true 

[+-] is a character class. It asserts that the string matches any character in the class.

#2

string.delete(op_str).size < string.size
  #=> true

See String#delete.

#3

string.tr(op_str, '').size < string.size
  #=> true

See String#tr.

#4

string.count(op_str) > 0
  #=> true 

See String#count.

#5

(string.chars & operators).any?
  #=> true 

See Array#&.

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.