Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to convert several instance variables into hash with ruby?

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.

like image 235
cbron Avatar asked Oct 03 '11 18:10

cbron


1 Answers

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}
like image 158
Lee Jarvis Avatar answered Sep 29 '22 01:09

Lee Jarvis