Skip to content

Instantly share code, notes, and snippets.

@wojtha
Created January 7, 2017 22:46
Show Gist options
  • Select an option

  • Save wojtha/079405558c82482dcdc231313982929f to your computer and use it in GitHub Desktop.

Select an option

Save wojtha/079405558c82482dcdc231313982929f to your computer and use it in GitHub Desktop.
class CastingStruct < Struct
def self.new(hash, &blk)
super(*hash.keys) do
define_method :initialize do |*args|
super *hash.values.map { |method|
args.shift.public_send method
}
end
class_eval(&blk) if blk
end
end
end
Person = CastingStruct.new name: :to_s,
age: :to_i,
category: :to_sym,
wage: :to_f
people = CSV.parse(data).map { |args| Person.new(*args) }
people.first
# => #<struct Person name="Dave", age=32, category=:employee, wage=15.75>
people.first.category.class
# => Symbol
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment