Search code examples
ruby-on-railsrubyconditional-statementswhitelist

passing string as a condition of a method in ruby


Is there a way to create a condition through string manipulation. here is the code where I attempted to pass a string as a condition into include? method.

"hello eveyone in the house".include?(%w('hello' 'world' 'new\ york'    'place').join(" || ").to_s)

Solution

  • An conditional as argument to include? is not possible, because include? accepts only a string argument.

    But you can write something like this:

    ['hello', 'world', 'new york', 'place'].any? { |word|
      "hello everyone in the house".include?(word)
    }
    

    Or you could generate a regexp from your strings:

    "hello eveyone in the house".match?(
      /#{['hello', 'world', 'new york', 'place'].join('|')}/
    )