简体   繁体   English

Ruby PrettyPrint单引号

[英]Ruby PrettyPrint in single quote

how to make Ruby pp function outputing String in valid (parsable) Ruby string using single quote if possible? 如果可能的话,如何使Ruby pp函数在有效(可分析)Ruby字符串中使用单引号输出String?

rows = [{name:'test',id:'182572'},{name:"Kal'el",id:'125125'}]
require 'pp'
pp rows

output was: 输出为:

[{:name=>"test", :id=>"182572"}, {:name=>"Kal'el", :id=>"125125"}]

desired output was: 所需的输出是:

[{:name=>'test', :id=>'182572'}, {:name=>"Kal'el", :id=>'125125'}]

(is it possible to use quote single quote inside single quote string?) (是否可以在单引号字符串内使用单引号?)

nevermind, i found the answer since my edit on sawa's answer has been rejected, i'll put it here: 没关系,因为我对sawa答案的编辑已被拒绝,所以我找到了答案,我将其放在此处:

class String
  alias :old_inspect :inspect
  def inspect
    return old_inspect if self.include? "'"
    "'#{self}'"
  end
end

You can't. 你不能 Strings, after parsing, aren't double or single quoted, they're just strings. 解析后的字符串不是双引号或单引号,它们只是字符串。 If you want strings to appear with single quotes, you'll have to write your own printing function. 如果希望字符串以单引号引起来,则必须编写自己的打印功能。

Redefine String#inspect . 重新定义String#inspect

class String
  def inspect; "'#{self}'" end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM