Marco Song Marco Song - 1 year ago 92
Ruby Question

Ruby: check whether a char is ( { [ using regular expression

I want to check whether a char is one of ( [ {

A can do it like this

if char == "{" || char == "(" || char == "["

but I want to use regular expression to achieve this.

How to do that?

Answer Source

It's pretty straight-forward, you just add them to a set:

BRACKETS = /[\{\(\[]/

if (char.match(BRACKETS))
  # ...

Where in a regular expression [...] represents a set of matching single characters.

To test that it's only that type of character:

BRACKETS = /\A[\{\(\[]\z/

Now the simplest refactoring of your code without using a regular expression is this:

case (char)
when '{', '(', '['
  # ...

That may or may not be faster than a regular expression, so if performance is key, you might want to test that approach as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download