Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Objects at Run-time in Ruby

Tags:

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?

like image 620
Levi Hackwith Avatar asked Sep 23 '10 03:09

Levi Hackwith


People also ask

How do you create an object 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.

What is the difference between a class and an object in Ruby?

An object is a unit of data. A class is what kind of data it is.

How is Ruby object-oriented?

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.


3 Answers

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"
like image 88
Mark Rushakoff Avatar answered Oct 17 '22 18:10

Mark Rushakoff


Use OpenStruct:

require 'ostruct'

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

my_object.name #=> "bob"
my_object.phone #=> "555-1212"
like image 43
horseyguy Avatar answered Oct 17 '22 18:10

horseyguy


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!

like image 30
Richard Cook Avatar answered Oct 17 '22 19:10

Richard Cook