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 t开发者_如何学Chis ?
edit: I just realized I can use instance_variable_get for that second part of that equation, but that still leaves the main problem.
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}
精彩评论