PascalTurbo
PascalTurbo

Reputation: 2363

Using setters together with instance_variable_set

I'm using this simple construct for initializing a class with a hash:

def initialize(params)
  params.each { |k, v| instance_variable_set("@#{k}", v) }
end

But instance_variable_set doesn't use the setter and so I can't handle special abilities. Is there an other nice way for initializing a class AND handle some extras in setter methods?

Upvotes: 2

Views: 217

Answers (2)

Andrew
Andrew

Reputation: 43113

Expanding on Logan's answer, you could do this to use defined setters and create accessors when not defined:

params.each do |name,value|
  if respond_to?("#{name}=")
    send "#{name}=", value
  else
    instance_variable_set "@#{name}",value
  end
end

Let me know if you have questions about the above and I can update the answer further.

Update

Or, as suggested by @mudasobwa, if you want there to be default accessor methods for all your instance variables, you could use this form:

params.each do |name,value|
  attr_accessor(name) unless respond_to?("#{name}=")
  send "#{name}=", value
end

Upvotes: 0

Logan Serman
Logan Serman

Reputation: 29870

You can use send to call the setter method on self:

params.each { |k, v| self.send("#{k}=", v) }

Upvotes: 3

Related Questions