PHP
<?PHP $dynamicProperties = array("name" => "bob","phone" => "555-1212"); $myObject = new stdClass(); foreach($dynamicProperties as $key => $value) { $myObject->$key = $value; } echo $myObject->name . "<br />" . $myObject->phone; ?>
我如何在ruby这样做?
解决方法
如果你想做一个“动态的”正式课,使用
Struct:
>> Person = Struct.new(:name,:phone) => Person >> bob = Person.new("bob","555-1212") => #<struct Person name="bob",phone="555-1212"> >> bob.name => "bob" >> bob.phone => "555-1212"
要使一个对象完全从一个哈希中完成,请使用OpenStruct:
>> require 'ostruct' => true >> bob = OpenStruct.new({ :name => "bob",:phone => "555-1212" }) => #<OpenStruct phone="555-1212",name="bob"> >> bob.name => "bob" >> bob.phone => "555-1212"