On Thu, Jan 27, 2011 at 6:30 PM, Kamarulnizam Rahim <niezam54 / hotmail.com>wrote:

> Im using the following code:
>
> class Target <
>  Struct.new(:question)
>  #Struct.new(:action, :blank, :cost, :status, :due_date,
> :responsibility)
>  def print_csv_record
>    # use the ternary operator to use one output format or the other
>    question.length==0 ? printf(",") : printf("\"%s\",", question)
>    printf("\n")
>  end
> end
>
>
This bit here is a little cumbersome, it could probably be cleaned up like
this:

class Target < Struct.new(:question)
  def print_csv_record
    print %("#{question}") if question && !question.length.zero?
    puts ","
  end
end

Though, I think a better way to do this would be to return the string, and
let the calling code decide how it should be dealt with (ie sent to $stdout,
like puts does, or maybe saved to a file instead, or manipulated further,
elsewhere)

CSV.open('ActionPlan.csv','rb').each do |row|
>  t = Target.new
>  t.question = row[1] if row[0].to_s.match(/1.[a-z]/)#maybe can use
> each.line
>  pp t.question #<---to test outputs
> end
>
>
Here, you open the file, then iterate over it, but never close it. To
iterate over its rows, try using foreach instead, which handles the file
upkeep for you.

Also, you see the nils, because you create a target on every iteration,
regardless of whether you assign it a question. So if you create the target,
and it does not match the regex, then it will not have a question. So when
you say 'pp t.question', t.question will be nil, so that is the same as 'pp
nil', and you will see nil. It isn't clear to me what you were actually
wanting to happen, so here are two possibilities.


1, Assumes you meant to use print_csv_record, which will just output a comma
for empty records
CSV.foreach('ActionPlan.csv') do |row|
  t = Target.new
  t.question = row[1] if row[0] =~ /1.[a-z]/
  t.print_csv_record
end

2. Assumes you wanted to skip output for rows that don't match your regex
CSV.foreach('ActionPlan.csv') do |row|
  next unless row[0] =~ /1.[a-z]/
  t = Target.new row[1]
  t.print_csv_record
end