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!
> 
> Many thanks for your assist!


class X

  attr_reader :vtype, :description

  def initialize(items)
     self.vtype = items[:vtype]
     self.description = items[:description]
  end

  def vtype=(val)
      if ["Ecar", "Fcar", "Gcar"].include?  val
        @vtype = val
      else
        puts "Error"
        @vtype = nil
      end
  end

  def description=(descr)
    if descr.length > 20
      puts "Error"
    else
      @description = descr
    end
  end
end

x = X.new(:vtype => "Ecar", :description => "Great Car")
puts x.vtype
puts x.description

-- 
Posted via http://www.ruby-forum.com/.