On Fri, Aug 28, 2009 at 6:03 AM, Pete Moran<pete / zoborg.com> wrote:
> Hi there,
>
> I am a total newbie to Ruby, so please bare with me.
>
> I want to be able to be able to initialise a Class with a hash. =A0For
> instance If I have the class
>
> class Vehicle
> =A0attr_accessor :vtype, :description, :vehicle, :capacity
> end
>
> I want to be able to do
>
> Vehicle.new(:vtype =3D> 'ECAR', :description =3D> 'Great Car', :vehicle =
=3D>
> 'Ford Focus', :capacity =3D> '10');
>
> Now I could do something like
>
> def initialize(items)
> =A0 =A0 @vtype =3D items[:vtype]
> =A0 =A0 @description =3D items[:description]
> =A0 =A0 @vehicle =3D items[:vehicle]
> =A0 =A0 @capacity =3D items[:capacity]
> # =A0 =A0 puts items.inspect
> =A0 end
>
> But I was wondering if there was a more generic way of doing this
> without specifically defining each variable in initialize? I think
> ActiveRecord does something similar!
>
> Many thanks for your assist!

Just playing devil's advocate, what about using OpenStruct?

require 'ostruct'

class Vehicle < OpenStruct

end

v1 =3D Vehicle.new(:vtype =3D> 'ECAR', :description =3D> 'Great Car', :vehi=
cle =3D>
'Ford Focus', :capacity =3D> '10')

I guess the concern would be the possibility of adding additional
accessors.  Using attr_accessor inside the class seems to keep me from
updating the variables.