Created
January 7, 2017 22:46
-
-
Save wojtha/079405558c82482dcdc231313982929f to your computer and use it in GitHub Desktop.
Ruby CastingStruct, taken from https://coderwall.com/p/e2qr2w/structs-with-type-casting-in-ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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