2009-09-22 30 views
2

我在寫一個將數據寫入文件的小型庫。一些數據是字符串,其中一些不是 - 諸如布爾(真/假)值之類的東西...Ruby:寫入文件時自動引用字符串,而不是其他數據?

當我有一個數據字符串時,我想將字符串寫入文件並用引號括起來。所以像「這是一串數據」這樣的字符串將被寫入文件中並用引號括起來。

當我有其他類型的數據,如布爾值,我想寫入文件的布爾值而不引用它周圍。所以,假將被寫爲假 - 周圍沒有引號。

有沒有辦法在寫入文件時自動引用/不引用變量的值,取決於保存值的變量是否是字符串?

回答

5

簡單的是#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 

但是對於一般類型,您可能需要考慮使用YAML或JSON。

+0

謝謝,rampion!這對我正在做的事情完美地起作用。 –

0

您是否嘗試過使用kind_of ?.

例子: variable.kind_of? String

1

這是做這件事:

if myvar.class == String 
    #print with quotes 
else 
    #print value 
end 
0

假設你的數據是文本類型,然後做

data.match(/true|false/).nil? ? "'#{data}'" : data 

應該是你想要的。

相關問題