Project

General

Profile

Feature #17155

Updated by janfri (Jan Friedrich) about 1 year ago

Ruby 2.3 introduced the ```#dig``` method as a general way to access elements in deep structures. Initially it was implemented only for ```Array``` and ```Hash```. In the meanwhile also the classes ```Struct```, ```OpenStruct``` and ```Set``` have a ```#dig``` method. There is also a [proposal](https://bugs.ruby-lang.org/issues/16425) to implement ```#dig``` for ```Thread```. 

 In my development I have own classes which have a ```#[]``` method implemented and are also candidates for a ```#dig``` method. But implementing ```#dig``` isn't so trivial as it seems: you have to handle some corner cases.    This is the intention for my proposal: Add a ```Diggable``` mixin to Ruby (core or stdlib). A simple implementation of it could be something like this: 

 ```Ruby 
 module Diggable 

  def dig *args 
    a = args.shift 
    o = self[a] 
    return o if args.empty? || o.nil? 
    o.send :dig, *args 
  end 

 end 
 ``` 

 So you could simply include ```Diggable``` to any class which implements ```#[],``` and you would get a ```#dig``` method for free. Like ```Comparable``` or ```Enumerable``` for which you have to implement ```#each``` respectively ```#<=>``` respectively ```#each``` and get other methods implemented in this mixins. 

Back