user1449980
user1449980

Reputation: 49

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

Upvotes: 0

Views: 180

Answers (3)

Anil
Anil

Reputation: 3919

Try this:

class A
  attr_accessor :x, :y, :z
end

a = A.new
my_hash = {:x => 1, :y => 2, :z => 3, :nono => 5}

If you do not have the list of attributes that can be assigned from the hash, you can do this:

my_attributes = (a.methods & my_hash.keys)

Use a.instance_variable_set(:@x = 1) syntax to assign values:

my_attributes.each do |attr|
  a.instance_variable_set("@#{attr.to_s}".to_sym, my_hash[attr])
end

Note(Thanks to Abe): This assumes that either all attributes to be updated have getters and setters, or that any attribute which has getter only, does not have a key in my_hash.

Good luck!

Upvotes: 0

Abe Voelker
Abe Voelker

Reputation: 31622

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)

Upvotes: 1

sczizzo
sczizzo

Reputation: 3206

Take a look at this article on Object initialization. You want an initialize method.

EDIT You might also take a look at this SO post on setting instance variables, which I think is exactly what you're trying to do.

Upvotes: 1

Related Questions