tommorris (owner)

Revisions

gist: 132199 Download_button fork
public
Description:
using frozen Structs as a Rubyish alternative to C# anonymous types
Public Clone URL: git://gist.github.com/132199.git
Text only
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 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)
=> #<Class:0x5f0244>
>> tom = person.new("tom", 24).freeze
=> #<struct #<Class:0x5f0244> 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
=> #<struct #<Class:0x5f0244> 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