tags:

views:

40

answers:

3

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?

+3  A: 

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"
Mark Rushakoff
What about doing something like `Bob = Object.new`?
Levi Hackwith
A: 

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!

Richard Cook
dude that's gross!!!
banister
It's totally hideous, I agree! Just illustrating the point that there are several different ways of doing things - I'm also pretty certain this is the kind of thing that `Struct` and `OpenStruct` are doing under the covers.
Richard Cook
A: 

Use OpenStruct:

require 'ostruct'

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

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