« Back to Index
Ruby: use Struct for inheritance chain
View original Gist on GitHub
Simple Struct Example.rb
s = Struct.new(:foo, :bar, :baz).new(1, 2, 3)
s.foo # => 1
s.bar # => 2
s.baz # => 3
Struct Complex Cache Example.rb
cache = Struct.new(nil) do
def set(key, value)
"key: #{key}, value: #{value}"
end
end.new
cache.set("k", "v") # => "key: k, value: v"
Struct Inheritance.rb
# Be warned: http://thepugautomatic.com/2013/08/struct-inheritance-is-overused/
class Foo < Struct.new(:bar, :baz)
def initialize(bar, baz)
super
end
end
foo = Foo.new('a', 'b') # => => #<struct Foo bar="a", baz="b">
foo.bar # => "a"
foo.baz # => "b"