2

i'm writing a small library that writes data out 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 the file with quotes around it. so a string like "this is a string of data" would be written to the file with the quotes around it.

when i have other types of data, like a boolean, I want to write the boolean value to the file without quotes around it. so, false would be written as false - no quotes around it.

is there a way to automatically quote / not quote the value of a variable, depending on whether or not the variable holding the value is a string, when writing to a file?

4 Answers 4

5

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 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

But for general types, you might want to consider YAML or JSON.

0
1

This is one way to do it:

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

Have you tried using kind_of?.

Example: variable.kind_of? String

0

Supposing that your data is of textual type, then doing

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

should be what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.