Levi Hackwith Levi Hackwith - 5 months ago 13
Ruby Question

Creating Objects at Run-time in 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;
?>


How do I do this in ruby?

Answer

If you want to make a "dynamic" formal class, use 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"

To make an object completely on-the-fly from a hash, use 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"
Comments