Creating Objects at Run-time in Ruby
PHP
<?php
$dynamicProperties = array("name" => "bob", "phone" => "555-1212");
$myObject = new stdClass();
foreach($dynamicProperties as $key => $v开发者_JAVA技巧alue) {
$myObject->$key = $value;
}
echo $myObject->name . "<br />" . $myObject->phone;
?>
How do I do this in ruby?
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"
Use OpenStruct:
require 'ostruct'
data = { :name => "bob", :phone => "555-1212" }
my_object = OpenStruct.new(data)
my_object.name #=> "bob"
my_object.phone #=> "555-1212"
One of many ways to do this is to use class_eval
, define_method
and so on to construct a class dynamically:
dynamic_properties = {
'name' => 'bob',
'phone' => '555-1212'
}
class_instance = Object.const_set('MyClass', Class.new)
class_instance.class_eval do
define_method(:initialize) do
dynamic_properties.each do |key, value|
instance_variable_set("@#{key}", value);
end
end
dynamic_properties.each do |key, value|
attr_accessor key
end
end
You can then consume this class later on as follows:
>> my_object = MyClass.new
>> puts my_object.name
=> 'bob'
>> puts my_object.phone
=> '555-1212'
But it wouldn't be Ruby if there was only one way to do it!
精彩评论