Section 2.24. Converting Strings to Numbers (Decimal and Otherwise)


2.23. Parsing Comma-Separated Data

Comma-delimited data are 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). There is also a somewhat improved tool called FasterCSV. Search for it online; it is not part of the standard Ruby distribution.




The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net