Search code examples
rubystring-matching

matching a double-quote via quote vs pattern


Why does check_char1 fail to find the double-quote?

#!/usr/bin/env ruby

line = 'hello, "bob"'

def check_char1(line, _char)
    puts "check_char1 found #{_char} in #{line}" if line =~ /_char/
end

check_char1(line, '"')

def check_char2(line, _char)
    puts "check_char2 found #{_char.inspect} in #{line}" if line =~ _char
end

check_char2(line, /"/)

...and can it be made to work using line =~ /_char/? (How should the double-quote be passed to the method?)


Solution

  • If _char is just a string (i.e. no regex pattern matching needed) then just use String#include?

    if line.include?(_char)
    

    If you must use a regex for this then Regexp.escape is your friend:

    if line =~ /#{Regexp.escape(_char)}/
    if line =~ Regexp.new(Regexp.escape(_char))
    

    and if you want _char to be treated like a regex (i.e. '.' matches anything) then drop the Regexp.escape:

    if line =~ /#{_char}/
    if line =~ Regexp.new(_char)