开发者

Determine whether a string contains any of a set of strings

开发者 https://www.devze.com 2023-02-07 03:16 出处:网络
I\'m using Mechanize to interact with a few web pages, and I\'m trying to determine whether a given form submission resulted in an error.

I'm using Mechanize to interact with a few web pages, and I'm trying to determine whether a given form submission resulted in an error.

Right now I'm doing this:

agent.page.body.include?("I'm an error message!")

But I just discovered another error message. Sinc开发者_运维技巧e I don't want to do:

agent.page.body.include?("I'm an error message!") || agent.page.body.include?("Another error message")

How can I determine whether the page body contains either error message?


error_messages.any? { |mes| agent.page.body.include? mes }


Alternatively, do it in one Regex pass:

error_messages = /I'm an error message!|Another error message/
if agent.page.body =~ error_messages
  ...
end

You'll need to ensure that you escape any error messages that contain special regex characters. To make it maintainable:

if agent.page.body =~ Regexp.union("foo", "bar", "jim.bob", "jam|jam")
  ...
end

You should only use this if you have tested and found the speed of Nakilon's answer is not enough, however. :)

0

精彩评论

暂无评论...
验证码 换一张
取 消