0

I'm looking for a way to iterate through a Ruby object's instance variables, and set them individually (from a provided hash) using a generic setter. I am assuming I can iterate through them directly in a method and simply set each individually.

Here is my object instance, u:

u = #<Waffle:0x00007fc6b1145530 
    @id=nil,
    @alpha="",
    @bravo="",
    @charlie="",
    @delta=nil,
    @echo=nil,
    @status=new>

I would like to populate it with a given hash, h:

h = {
    "id"=>"141",
     "alpha"=>"Muccahiya""
     "bravo"=>"$2a$10$xR2g",
     "charlie"=>"2018-02-21 10:41:56-05",
     "delta"=>"2018-02-05 18:17:16.752606-05",
     "echo"=>"wobbly",
     "status"=>"active"
}

This is the method I have and it is throwing this error:

def to_obj(h)
    self.instance_variables.each do |i|
        self.i = h[i.sub('@','')]
    end
end

Error:

Traceback (most recent call last):
3: from /users/rich/app.rb:31:in `<main>'
2: from /Library/WebServer/Documents/dingbat/models/waffle.rb:240:in `to_obj'
1: from /Library/WebServer/Documents/dingbat/models/waffle.rb:240:in `each'
/Library/WebServer/Documents/dingbat/models/waffle.rb:241:in `block in to_obj': no implicit conversion of String into Integer (TypeError)

self.instance_variables is indeed an array of symbols.

I am thinking that an object can set its instance_variables given a hash. This can't be difficult.

1
  • 2
    You want instance_variable_set method Commented Feb 8, 2018 at 9:01

1 Answer 1

4
def to_obj(h)
  h.each{|k, v| instance_variable_set("@{k}", v)}
end

If you want to set a value only if such instance variable is defined, then do:

def to_obj(h)
  h.each do
    |k, v|
    next unless instance_variable_defined?("@{k}")
    instance_variable_set("@{k}", v)
  end
end
Sign up to request clarification or add additional context in comments.

11 Comments

For security reasons, I'm iterating the object's ivars and setting accordingly from the hash, instead of the other way around. Cheers
@SergioTulentsev The provided hash could be larger than the array of instance_variables I want to actually modify. So if I qualify the instance_variables, I can only set those, instead of having the hash take the lead.
@Stefan: yes, but if something were to set an "unknown" instance variable, it wouldn't be used by anything (except maybe reflection-based serialization or something). Plus, this mass-assign is "unpredicable" (depends on what instance variables in the object are "alive" at the moment)
@Rich_F: if you whitelist "settable" instance variables (of which we have no evidence in this thread) - then yes. but in this case you might just as well filter hash keys. It's the whitelisting that adds security, not the inversion.
@SergioTulentsev instance_variables seems to be that whitelist.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.