ruby code for modifying outer quotes on strings?

前端 未结 3 733
孤城傲影
孤城傲影 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.

    0 讨论(0)
  • 2021-01-19 07:14

    I would use the value = value[1...-1] if value[0] == value[-1] && %w[' "].include?(value[0]). In short, this simple code checks whether first and last char of string are the same and removes them if they are single/double quote. Additionally as many as needed quote types can be added.

    %w["adadasd" 'asdasdasd' 'asdasdasd"].each do |value|
      puts 'Original value: ' + value
      value = value[1...-1] if value[0] == value[-1] && %w[' "].include?(value[0])
      puts 'Processed value: ' + value
    end
    

    The example above will print the following:

    Original value: "adadasd"
    Processed value: adadasd
    Original value: 'asdasdasd'
    Processed value: asdasdasd
    Original value: 'asdasdasd"
    Processed value: 'asdasdasd"
    
    0 讨论(0)
  • 2021-01-19 07:20

    This might 'splain how to remove and add them:

    str1 = %["We're not in Kansas anymore."]
    str2 = %['He said, "Time flies like an arrow, Fruit flies like a banana."']
    
    puts str1
    puts str2
    
    puts
    
    puts str1.sub(/\A['"]/, '').sub(/['"]\z/, '')
    puts str2.sub(/\A['"]/, '').sub(/['"]\z/, '')
    
    puts 
    
    str3 = "foo"
    str4 = 'bar'
    
    [str1, str2, str3, str4].each do |str|
      puts (str[/\A['"]/] && str[/['"]\z/]) ? str : %Q{"#{str}"}
    end
    

    The original two lines:

    # >> "We're not in Kansas anymore."
    # >> 'He said, "Time flies like an arrow, Fruit flies like a banana."'
    

    Stripping quotes:

    # >> We're not in Kansas anymore.
    # >> He said, "Time flies like an arrow, Fruit flies like a banana."
    

    Adding quotes when needed:

    # >> "We're not in Kansas anymore."
    # >> 'He said, "Time flies like an arrow, Fruit flies like a banana."'
    # >> "foo"
    # >> "bar"
    
    0 讨论(0)
提交回复
热议问题