From: "David A. Black" Date: 2009-08-28T20:24:19+09:00 Subject: Re: Mass Assignment on Clas Hi -- On Fri, 28 Aug 2009, Pete Moran 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. For > instance If I have the class > > class Vehicle > attr_accessor :vtype, :description, :vehicle, :capacity > end > > I want to be able to do > > Vehicle.new(:vtype => 'ECAR', :description => 'Great Car', :vehicle => > 'Ford Focus', :capacity => '10'); > > Now I could do something like > > def initialize(items) > @vtype = items[:vtype] > @description = items[:description] > @vehicle = items[:vehicle] > @capacity = items[:capacity] > # puts items.inspect > 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! How about: def initialize(items) items.each do |key,value| instance_variable_set("@#{key}", value) end end (possible with some checking to make sure they're what you want). David -- David A. Black / Ruby Power and Light, LLC / http://www.rubypal.com Q: What's the best way to get a really solid knowledge of Ruby? A: Come to our Ruby training in Edison, New Jersey, September 14-17! Instructors: David A. Black and Erik Kastner More info and registration: http://rubyurl.com/vmzN