What is the best syntax for comparing one line with several other lines?

I am mainly looking for a more beautiful way to write:

do_something() if my_string == 'first' | my_string == 'second' | my_string == 'third'

Any ideas?

+3
source share
4 answers

The most common solution is to use Array#include?:

do_something if %w(first second third).include? my_string
+9
source
do_something() if ['first', 'second', 'third'].include? my_string
0
source

do_something if my_string =~ /^(first|second|third)$/

0

/ , , , , :

require 'set'
SPECIAL_VALUES = Set["first", "second", "third"]

def foo(my_string)
  do_something if SPECIAL_VALUES.include?(my_string)
end

"", "" .., Hash Set.

0

Source: https://habr.com/ru/post/1753591/


All Articles