5

I'm getting a response in the format of

 #<Response:0x000...   @first = "Charlie", @last=Kelly, ....

and I need to turn this into a hash (for active merchant). Currently I am looping through the variables and doing this:

response.instance_variables.each do |r|
  my_hash.merge!(r.to_s.delete("@").intern => response.instance_eval(r.to_s.delete("@"))) 
end

This works, it will produce {:first = "charlie", :last => "kelly"} , but it seems a bit hacky and unstable. Is there a better way to do this ?

edit: I just realized I can use instance_variable_get for that second part of that equation, but that still leaves the main problem.

0

1 Answer 1

9

Rails has a method on Object called instance_values for just this. Here's the code on GitHub.

class C
  def initialize(x, y)
    @x, @y = x, y
  end
end

C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
C.new(0, 1).instance_values.symbolize_keys # => {:x => 0, :y => 1}
Sign up to request clarification or add additional context in comments.

4 Comments

Is there any way I can force the first value into a symbol instead of a string ? I can't touch the code that's receiving this, and strings aren't working.
Sure, .symbolize_keys: obj.instance_values.symbolize_keys should get you going!
Aww perfect man. I started to re-write that instance_values method but this is way easier. Grazie.
No problem, Rails usually has helpers for this kinda stuff, you just have to dig. Happy coding!

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.