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?
You can create objects in Ruby by using the method new of the class. The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods. Here, cust1 and cust2 are the names of two objects.
An object is a unit of data. A class is what kind of data it is.
Ruby is a pure object-oriented language and everything appears to Ruby as an object. Every value in Ruby is an object, even the most primitive things: strings, numbers and even true and false. Even a class itself is an object that is an instance of the Class class.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With