Re: Ruby Quiz is Back - Challenge #1 - Read Comma-Separated Values (CSV) from the "Real World"

Gerald Bauer <[email protected]>
Newsgroups gmane.comp.lang.ruby.general
Message-ID <CAAxEZd8XFNTdfemf6kAFwRrqovqHzKM-JeZRVj-BHEq9zvAO0w@mail.gmail.com>
Hello,
   sorry for the "minified" code snippet version for the Ruby Quiz #1.
Trying again (looks good in the email preview):

---
class CSV
  include Mealy

  initial_state(:start) { @line = []; @text = '' }

  read(state: :start, on: "\n")

  transition(from: :start, to: :comment, on: '#')
  transition(from: :comment, to: :start, on: "\n")
  read(state: :comment)


  transition from: [:normal, :start], to: :quote, on: '"'
  transition from: :quote, to: :normal, on: '"'

  transition(from: :start, to: :normal, on: ',') { @line << '' }
  transition(from: :start, to: :normal, on: ' ')
  transition(from: :start, to: :normal) { |c| @text << c }
  transition(from: :normal, to: :start, on: "\n") do
    emit @line << @text; @line = []; @text = ''
  end

  read state: :normal, on: ' '
  read(state: :normal, on: ',') {  @line << @text; @text = '' }

  read(state: [ :normal, :quote ]) { |c| @text << c }

  finish { emit @line unless @line.empty? }
end

def parse(text)
  CSV.new.run(text.chars).entries
end
---


  Happy hacking and data wrangling with Ruby.

Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.