[ruby] 루비는 객체를 해시로 변환

& Gift객체를 가지고 있다고 가정 해 봅시다 . Rails가 아닌 Ruby 에서 해시로 변환하는 가장 좋은 방법은 무엇입니까 ? (Rails도 자유롭게 대답 할 수는 있지만)?@name = "book"@price = 15.95{name: "book", price: 15.95}



답변

class Gift
  def initialize
    @name = "book"
    @price = 15.95
  end
end

gift = Gift.new
hash = {}
gift.instance_variables.each {|var| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }
p hash # => {"name"=>"book", "price"=>15.95}

다른 방법으로 each_with_object:

gift = Gift.new
hash = gift.instance_variables.each_with_object({}) { |var, hash| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }
p hash # => {"name"=>"book", "price"=>15.95}


답변

그냥 말해 (현재 개체) .attributes

.attributes의를 반환 hash합니다 object. 그리고 훨씬 더 깨끗합니다.


답변

구현 #to_hash?

class Gift
  def to_hash
    hash = {}
    instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) }
    hash
  end
end


h = Gift.new("Book", 19).to_hash


답변

Gift.new.instance_values # => {"name"=>"book", "price"=>15.95}


답변

as_json방법 을 사용할 수 있습니다 . 객체를 해시로 변환합니다.

그러나 해시는 해당 객체의 이름에 키로 사용됩니다. 귀하의 경우

{'gift' => {'name' => 'book', 'price' => 15.95 }}

객체에 저장된 해시가 필요한 경우을 사용하십시오 as_json(root: false). 나는 기본적으로 루트가 거짓이라고 생각합니다. 자세한 내용은 공식 루비 가이드를 참조하십시오

http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json


답변

활성 레코드 객체

module  ActiveRecordExtension
  def to_hash
    hash = {}; self.attributes.each { |k,v| hash[k] = v }
    return hash
  end
end

class Gift < ActiveRecord::Base
  include ActiveRecordExtension
  ....
end

class Purchase < ActiveRecord::Base
  include ActiveRecordExtension
  ....
end

그런 다음 전화

gift.to_hash()
purch.to_hash() 


답변

Rails 환경에 있지 않은 경우 (즉, ActiveRecord를 사용할 수없는 경우) 도움이 될 수 있습니다.

JSON.parse( object.to_json )