# Simon Harriyott (@harriyott) asked on Twitter how to replicate C# anonymous types # in Ruby. Here's how I would do it. # I don't know C#. MSDN says anonymous types "provide a convenient way to encapsulate # a set of read-only properties into a single object without having to first # explicitly define a type" # we can use a struct to do something similar: >> person = Struct.new(:name, :age) => # >> tom = person.new("tom", 24).freeze => # name="tom", age=24> # or you could do Struct.new(:name, :age).new("tom", 24).freeze # The freeze method call makes the new object read-only. >> tom.name = "bar" TypeError: can't modify frozen Struct from (irb):7:in `name=' from (irb):7 # But we can always make a writable copy using the dup method. >> tom = tom.dup => # name="tom", age=24> >> tom.frozen? => false # Of course, if the data is simple, one doesn't need to use a Struct # - rather just use a Hash, Array or String or whatever. Or use class << obj; # And you can always use internal/dl hacking as an *evil* # alternative to .dup() # http://eigenclass.org/hiki/evil.rb+dl+and+unfreeze