在Ruby中运行时创建对象

时间:2010-09-23 03:04:14

标签: 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中执行此操作?

3 个答案:

答案 0 :(得分:27)

如果您想制作“动态”正式课程,请使用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"

答案 1 :(得分:6)

使用OpenStruct:

require 'ostruct'

data = { :name => "bob", :phone => "555-1212" }
my_object = OpenStruct.new(data)

my_object.name #=> "bob"
my_object.phone #=> "555-1212"

答案 2 :(得分:4)

执行此操作的众多方法之一是使用class_evaldefine_method等来动态构建类:

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

您可以稍后使用此类,如下所示:

>> my_object = MyClass.new
>> puts my_object.name
=> 'bob'
>> puts my_object.phone
=> '555-1212'

但如果只有一种方法,那就不是Ruby了!