我正在写一个小数据库,将数据写入文件.一些数据是字符串,其中一些不是 - 像boolean(true/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"
您可以在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
Run Code Online (Sandbox Code Playgroud)
但对于一般类型,您可能需要考虑YAML或JSON.
| 归档时间: |
|
| 查看次数: |
460 次 |
| 最近记录: |