Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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