Anonymous Types in Ruby

Posted by Josh Wright | Posted in Code | Posted on August 5, 2010

Aug 5

Anonymous Types in C#

Anonymous types are new in C# 3.5 and while they are easily abused, they greatly simplify certain tasks.  You can’t dynamically add a property and your scope is pretty limited, but here’s how it looks:

1
2
var o = new { Name = "Josh", Age = 28 };
Console.WriteLine(o.Name); // Josh

Dynamics in C#

Dynamics in C# 4.0 didn’t solve the problem like I thought. Scope is no longer an issue (you can pass ‘dynamic’ objects around), but you still can’t dynamically add a property.

1
2
dynamic o = new { Name = "Josh" };
o.Age = 28;  // BLOWS UP AT RUNTIME

Actually there is an expando object (i kid you not) that seems to wrap a Dictionary that will allow dynamic property creation.

1
2
dynamic o = new ExpandoObject(new { Name = "Josh" });
o.Age = 28;  // WORKS

Hashes in Ruby

I’ve been learning Ruby and what interested me most was how dynamic it is. I expected to be able to do something like this:

1
2
3
4
5
o = { "Name" => "Josh" };
puts o["Name"]  # Work correctly

puts o.Name  # Does not work
o.Age = 28  # Not possible

But hash values aren’t accessible through properties. And likewise values cannot be added to a hash via properties.

OpenStruct in Ruby

But as always with Ruby, “there’s a lib for that” and it’s OpenStruct. You can start it out with a hash (or not) and you can dynamically access and create properties… very similar to ExpandoObject in C#.

1
2
3
4
5
o = OpenStruct.new({ "Name" => "Josh" });

puts o.Name  # Writes "Josh"
o.Age = 28  # Creates "Age" property
o.NonExistantProperty # Returns nil

Write a comment