在Ruby中运行时创建对象

前端之家收集整理的这篇文章主要介绍了在Ruby中运行时创建对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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"
原文链接:https://www.f2er.com/ruby/267168.html

猜你在找的Ruby相关文章