2013-05-30 42 views
0

我有以下散列:動態填充的Ruby對象的屬性,其屬性名相同的哈希鍵

row = {:id => 1, :name => "Altus Raizen", :email => "[email protected]"} 

現在我有一個Person結構與row相同的屬性鍵:

Person = Struct.new(:id, :name, :email) 

欲動態填充利用在row散列值的Person對象如下:

person = Person.new 
person.id = row[:id] 
person.name = row[:name] 
person.email = row[:email] 

上面的代碼工作正常,但必須有一個更優雅的方式來完成此操作,即動態填充屬性。我該怎麼做呢? (我實際上有9個屬性,所以通過考慮將值設置爲其他屬性(如電話,地址等),上面的代碼變得更長和更「醜陋」)。

回答

6
person = Person.new 
row.each_pair { |key, value| person.send("#{key}=", value) } 
2

紅寶石> = 1.9。你可以這樣做:

row = {:id => 1, :name => "Altus Raizen", :email => "[email protected]"} 
Person = Struct.new(:id, :name, :email) 

p person = Person.new(*row.values) 
# => <struct Person id=1, name="Altus Raizen", email="[email protected]"> 

由於所有事情都按照正確的順序,所以發生了這種情況。更多的控制,使values_at,這也適用於舊的紅寶石:

row = {:id => 1, :name => "Altus Raizen", :email => "[email protected]"} 
Person = Struct.new(:id, :name, :email) 
p person = Person.new(*row.values_at(:id, :name, :email)) 

另一種選擇是OpenStruct:

用於運行或代碼玩
require 'ostruct' 
row = {:id => 1, :name => "Altus Raizen", :email => "[email protected]"} 
person = OpenStruct.new(row) 
p person #=><OpenStruct id=1, name="Altus Raizen", email="[email protected]"> 
puts person.name #=> Altus Raizen 
+0

的編輯器?好奇心問道。 –