On Thu, May 5, 2011 at 4:19 PM, Jolyon R. <jolyonruss / gmail.com> wrote:
> Wow, thanks for the plentiful replies!
>
> I think I was averse to creating multiple classes in one file, so
> thought it best to try and create the CsvRow inline, it had crossed my
> mind but I got hung up on the semantics of the book asking for an
> object.
>
> I create a CsvRow class and am now getting an each to return a CsvRow,
> AWESOME!
>
> The next bit I'm getting a little caught up on is how to get CsvRow to
> return a single value in a row based on a headers value.
>
> When I store a line in my CsvRow like this:
>
> @fields =3D line.chomp.split(', ')
>
> Is that an array or hash?

Array.  You can try that easily in IRB.  It's really a helpful tool.

> Using method_missing and it's an array will this work:
>
> class CsvRow
> =A0attr_reader :fields, :headersPattern
>
> =A0def initialize(line)
> =A0 =A0@fields =3D line.chomp.split(', ')
> =A0end
>
> =A0def headerPattern( pattern )
> =A0 =A0@headersPattern =3D pattern
> =A0end
>
> =A0def self.method_missing name, *args
> =A0 =A0 / headersPattern.each_with_index |header, index|
> =A0 =A0 =A0if header =3D name.to_s yield @fields.send(@headers[index])
> =A0 =A0end
> =A0end
> end

Not sure what the method above is intended to do.  First odd thing is
that it is not defined in your CsvRow class as instance method.
That's likely not what you want.

Then, there is a typo: you have "=3D" instead of "=3D=3D".  If you
identified a match you rather want to return the value instead of
using yield.

Maybe you had something in mind like

def method_missing name, *args, &b
  @header_pattern.each_with_index do |hd, idx|
    return @fields[idx] if hd =3D=3D name
  end
  super # default error handling
end

Or you could do

def method_missing name, *args, &b
  idx =3D @header_pattern.index name.to_s and return @fields[idx]
  super # default error handling
end

A general remark: conventionally we use underscore_case for method and
variable names.  CamelCase is only used for constants (class names and
the like).

One last remark: you can make your live easier and do

class CsvRow
  attr_reader :fields
  attr_accessor :headers_pattern
end

> Thanks again for your help, it really makes a difference knowing a
> language has a community of helpful people behind it :)

Absolutely!  I'd say Ruby community is one of the friendliest places
you can hang out.

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/