Last active
          May 21, 2019 13:15 
        
      - 
      
 - 
        
Save ohthatjames/60a0b219443aeeb6cb41 to your computer and use it in GitHub Desktop.  
    Registering to_procs without monkeypatching everything
  
        
  
    
      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
    
  
  
    
  | 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