Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

2.23 Parsing Comma-Separated Data

The use of comma-delimited data is common in computing. It is a kind of “lowest common denominator” of data interchange used (for example) to transfer information between incompatible databases or applications that know no other common format.

We assume here that we have a mixture of strings and numbers and that all strings are enclosed in quotes. We further assume that all characters are escaped as necessary (commas and quotes inside strings, for example).

The problem becomes simple because this data format looks suspiciously like a Ruby array of mixed types. In fact, we can simply add brackets to enclose the whole expression, and we have an array of items:

string = gets.chop!
# Suppose we read in a string like this one:
# "Doe, John", 35, 225, "5'10\"", "555-0123"
data = eval("[" + string + "]")   # Convert to array
data.each {|x| puts "Value = #{x}"}

This fragment produces the following output:

Value = Doe, John
Value = 35
Value = 225
Value = 5' 10"
Value = 555-0123

For a more heavy-duty solution, refer to the CSV library (which is a standard library).

  • + Share This
  • 🔖 Save To Your Account