Search code examples
ruby-on-railsrubyclass-variables

Initializing a variable RUBY


I have a class Sample

Sample.class returns

(id :integer, name :String, date :date)

and A hash has all the given attributes as its keys. Then how can I initialize a variable of Sample without assigning each attribute independently.

Something like

Sample x = Sample.new

x.(attr) = Hash[attr]

How can I iterate through the attributes, the problem is Hash contains keys which are not part of the class attributes too


Solution

  • class Sample
      attr_accessor :id, :name, :date
    end
    
    h = {:id => 1, :name => 'foo', :date => 'today', :extra1 => '', :extra2 => ''}
    
    init_hash = h.select{|k,v| Sample.method_defined? "#{k}=" }
    
    # This will work
    s = Sample.new
    init_hash.each{|k,v| s.send("#{k}=", v)}
    
    # This may work if constructor takes a hash of attributes
    s = Sample.new(init_hash)