[LRUG] Dumb question: keyword arg parsing / Struct

Damian Janowski djanowski at dimaion.com
Tue Aug 10 06:22:28 PDT 2010


On Tue, Aug 10, 2010 at 9:08 AM, Daniel Barlow <dan at telent.net> wrote:
> OK, I'm sure this is one of those things that everyone else knows about
> except me[*], but Googling is getting me nowhere.
>
> Is there a gem or a standard idiom for creating Struct-like classes whose
> #new method accepts named parameters (corresponding to the accessor names)
> instead of arguments by order?  I would like to write, for example

OpenStruct can take a hash in the initializer, so I think that's what you need.

>  class Book < NamedStruct.new(:isbn,:author,:title,:review_rating)
>  b=Book.new(:author=>'Ian McDonald',:title=>'Brasyl')

Alternatively, you can do:

Book = OpenStruct.new(...)

> If there isn't then I could probably stand to improve my understanding of
> Ruby metaprogramming significantly by writing my own, but it seems like the
> kind of wheel that must have been reinvented many times already, and surely
> by now someone has made a nice smooth round one

Why not taking a shot at it anyways? The implementation is not too
long – and it's a fun exercise!



More information about the Chat mailing list