I am new to Ruby. Is there a way to write a single ‘def Array/Range/Hash’ with a method_missing that will work for all Ranges, Arrays and Hash i.e. all Enumerables? For e.g. the following should work:
[1..5].Sum()
[1,2,3,5].Sum()
{'x' => 1, 'y' = 4}.Sum()
Sum() is our custom method defined inside method_missing. As of now, I have written three different functions that handle method_missing for Array, Range and Hash separately.
You can define
method_missingfor all Enumerables by openingEnumerablemodule and adding an instance method to it:But I would recommend to define concrete
summethod (starts with lower case letter, according to Ruby methods naming guidelines) instead of adding this logic tomethod_missing: