Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created May 15, 2012 12:25
Show Gist options
  • Save JoshCheek/2701369 to your computer and use it in GitHub Desktop.
Save JoshCheek/2701369 to your computer and use it in GitHub Desktop.
class MyStruct
def self.new(*method_names, &block)
raise ArgumentError, "wrong number of arguments (0 for 1+)" if method_names.empty?
Class.new do
class_eval &block if block
include Enumerable
def initialize(*args)
@attributes = Hash[members.map(&:to_s).zip args]
end
def inspect
"#<struct #{@attributes.map { |key, value| "#{key}=#{value.inspect}"}.join ', '}>"
end
def size
members.size
end
def values
@attributes.values
end
def each(&block)
values.each(&block)
end
def select(&block)
values.select &block
end
def [](key)
key = key.to_s
raise NameError, "no member '#{key}' in struct" unless @attributes.has_key? key
@attributes[key]
end
def []=(key, value)
key = key.to_s
raise NameError, "no member '#{key}' in struct" unless @attributes.has_key? key
@attributes[key] = value
end
define_method :members do
method_names
end
method_names.each do |method_name|
raise TypeError, "#{method_name} is not a symbol" unless method_name.kind_of? Symbol
define_method method_name do
@attributes[method_name.to_s]
end
define_method "#{method_name}=" do |arg|
@attributes[method_name.to_s] = arg
end
end
end
end
end
@JoshCheek
Copy link
Author

Original problem here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment