Ruby: auto quote string, not other data, when writing to file?

I am writing a small library that writes data to a file. some of the data is strings, some of it is not - things like boolean (true / false) values ​​...

when I have a string for data, I want to write the string to a file with quotes around it. so a string like "this is a data string" will be written to the file with quotes around it.

when I have other data types like booleans, I want to write boolean to a file without quotes around it. so false will be written as false - no quotes around it.

is there a way to automatically specify / not specify the value of a variable depending on whether the variable containing the value is a string when written to a file?

+2


source to share


4 answers


The simplest is #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 check it on 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

      

But for generic types, you might consider YAML or JSON.

+5


source


This is one way to do it:



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

      

+1


source


Have you tried using kind_of ?.

Example: variable.kind_of? String

0


source


Let's assume your data is of text type, then do

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

      

should be what you want.

0


source







All Articles