This post originated from an RSS feed registered with Ruby Buzz
by Red Handed.
Original Post: How Do You Parse Tab Separated Values
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
How to parse tab separated values, values of which may be omitted and they should be recognized as nil—that was discussed at ruby-list.
For instance each row has three values: float, integer and string; “1\t2\t3”
should be 1.0, 2, “3”. When values are omitted they should be parsed as nil,
not zero nor empty string; “1\t\t3” should be 1.0, nil, “3”.
class TextData < Struct.new(:float, :int, :str)
CONVERTER = [:to_f, :to_i, :to_s]
def self.[](input)
obj = new
input.chomp.split(/\t/).each_with_index do |x, i|
obj[i] = (x && x.__send__(CONVERTER[i]))
end
obj
end
end
p TextData["1\t2\t3"]
p TextData["1.0\t2\t"]
p TextData["1\t2\tfoo"]
#
#
#
Inherit an anonymous structure class!
1 He is a pioneer of Ruby. I learned
Ruby techniques from his book and home page.
“Rubikichi” is his alias.
There is extra functionality in the original question, which I skip here; converting the string value is required.