Anonymous Types in Ruby

By Josh Wright on August 2010 in tips


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:

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.

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.

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:

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#.

o ={ "Name" => "Josh" });

puts o.Name # Writes "Josh"

o.Age = 28 # Creates "Age" property

o.NonExistantProperty # Returns nil