TheMayerof
TheMayerof

Reputation: 193

Ruby, checking if an item exists in an array using Regular expression

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

Upvotes: 0

Views: 68

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

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#&.

Upvotes: 0

Stefan
Stefan

Reputation: 114168

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

Upvotes: 1

Related Questions