Anonymous Types in Ruby

59 sec read

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:

</p>
<p>var o = new { Name = "Josh", Age = 28 };</p>
<p>Console.WriteLine(o.Name); // Josh</p>
<p>

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.

</p>
<p>dynamic o = new { Name = "Josh" };</p>
<p>o.Age = 28; // BLOWS UP AT RUNTIME</p>
<p>

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

</p>
<p>dynamic o = new ExpandoObject(new { Name = "Josh" });</p>
<p>o.Age = 28; // WORKS</p>
<p>

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:

</p>
<p>o = { "Name" => "Josh" };</p>
<p>puts o["Name"] # Work correctly</p>
<p>puts o.Name # Does not work</p>
<p>o.Age = 28 # Not possible</p>
<p>

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

</p>
<p>o = OpenStruct.new({ "Name" => "Josh" });</p>
<p>puts o.Name # Writes "Josh"</p>
<p>o.Age = 28 # Creates "Age" property</p>
<p>o.NonExistantProperty # Returns nil</p>
<p>

Leave a Reply

Your email address will not be published.