Marco Song Marco Song - 29 days ago 6
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

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

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

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

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 '{', '(', '['
  # ...
end

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.