ruby code for modifying outer quotes on strings?

前端 未结 3 736
孤城傲影
孤城傲影 2021-01-19 06:28

Does anyone know of a Ruby gem (or built-in, or native syntax, for that matter) that operates on the outer quote marks of strings?

I find myself writing methods like

3条回答
  •  滥情空心
    2021-01-19 07:09

    If you do it a lot, you may want to add a method to String:

    class String
      def strip_quotes
        gsub(/\A['"]+|['"]+\Z/, "")
      end
    end
    

    Then you can just call string.strip_quotes.

    Adding quotes is similar:

    class String
      def add_quotes
         %Q/"#{strip_quotes}"/ 
      end
    end
    

    This is called as string.add_quotes and uses strip_quotes before adding double quotes.

提交回复
热议问题