gpt4 book ai didi

Ruby:写入文件时自动引用字符串,而不是其他数据?

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:31 24 4
gpt4 key购买 nike

我正在编写一个将数据写入文件的小型库。有些数据是字符串,有些不是——比如 bool 值(真/假)……

当我有一个数据字符串时,我想将该字符串用引号括起来写入文件。因此,像“这是一串数据”这样的字符串将被写入文件,并在其周围加上引号。

当我有其他类型的数据时,比如 bool 值,我想将 bool 值写入文件而不用引号引起来。所以,false 会写成 false - 周围没有引号。

有没有办法在写入文件时自动引用/不引用变量的值,这取决于保存该值的变量是否是字符串?

最佳答案

最简单的是#inspect

--------------------------------------------------------- Object#inspect     obj.inspect   => string------------------------------------------------------------------------     Returns a string containing a human-readable representation of     _obj_. If not overridden, uses the +to_s+ method to generate the     string.        [ 1, 2, 3..4, 'five' ].inspect   #=> "[1, 2, 3..4, \"five\"]"        Time.new.inspect                 #=> "Wed Apr 09 08:54:39 CDT 2003"

You can test it out in IRB.

irb> "hello".inspect
#=> "\"hello\""
irb> puts _
"hello"
#=> nil
irb> true.inspect
#=> "true"
irb> puts _
true
#=> nil
irb> (0..10).to_a.inspect
#=> "[0,1,2,3,4,5,6,7,8,9,10]"
irb> puts _
[0,1,2,3,4,5,6,7,8,9,10]
#=> nil

但对于一般类型,您可能需要考虑 YAML 或 JSON。

关于Ruby:写入文件时自动引用字符串,而不是其他数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1462654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com