开发者

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

开发者 https://www.devze.com 2023-04-10 02:05 出处:网络
I\'m getting a response in the format of #<Response:0x000...@first = \"Charlie\", @last=Kelly, ....

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}
0

精彩评论

暂无评论...
验证码 换一张
取 消