The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
How Do You Parse Tab Separated Values

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Red Handed

Posts: 1158
Nickname: redhanded
Registered: Dec, 2004

Red Handed is a Ruby-focused group blog.
How Do You Parse Tab Separated Values Posted: Apr 28, 2005 8:58 AM
Reply to this message Reply

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
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Red Handed
Latest Posts From RedHanded

Advertisement

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

# 
# 
# 

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.

Read: How Do You Parse Tab Separated Values

Topic: taskthis! for postgresql Previous Topic   Next Topic Topic: ecto 2.3 is out

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use