Skip to content

Instantly share code, notes, and snippets.

@ohthatjames
Last active May 21, 2019 13:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohthatjames/60a0b219443aeeb6cb41 to your computer and use it in GitHub Desktop.
Save ohthatjames/60a0b219443aeeb6cb41 to your computer and use it in GitHub Desktop.
Registering to_procs without monkeypatching everything
require "set"
class Proc
def self.register_type(klass, proc)
@types_to_convert ||= {}
@types_to_convert[klass] = proc
end
def self.[](field)
-> (x) { (@types_to_convert || {})[field.class].call(field, x) }
end
end
Proc.register_type(Set, ->(set, x) { x if set.include?(x) })
Proc.register_type(Hash, ->(hash, x) { hash[x] })
Proc.register_type(Array, ->(array, x) { array[x] })
perfect_numbers = Set[6, 28, 496]
puts (1..30).select(&Proc[perfect_numbers]).inspect
# => [6, 28]
person = { name: "Robert Paulson", age: 43 }
puts [:name, :age].map(&Proc[person]).inspect
# => ["Robert Paulson", 43]
puts (1..3).map(&Proc[["A", "B", "C", "D", "E"]]).inspect
# => ["B", "C", "D"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment