ruby code for modifying outer quotes on strings?

前端 未结 3 755
孤城傲影
孤城傲影 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: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"
    

提交回复
热议问题