How Do You Parse Tab Separated Values #
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”.
Following is a solution of Rubikichi-san1.
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"]
# <struct TextData float=1.0, int=2, str="3">
# <struct TextData float=1.0, int=2, str=nil>
# <struct TextData float=1.0, int=2, str="foo">
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.
chris2
How about the more functional
rubnewb
Looks interesting…would love a line by line commentary. I’m new to Ruby but felt I had a good handle on most of what you can do until I saw this!
doug
chris2: looks good, but how is it more functional?
doug
ah, as in functional programming
chris2
There you go:
chris2
doug: Exactly.
why
That is soo righteous!!
Bil
Except for the lack of
test/unit
. ;)(Hey, why all the space around
test/unit
?)Comments are closed for this entry.