ruby - Single method_missing for Array, Hash and Range -
i new ruby. there way write single 'def array/range/hash' method_missing work ranges, arrays , hash i.e. enumerables? e.g. following should work:
[1..5].sum() [1,2,3,5].sum() {'x' => 1, 'y' = 4}.sum()
sum() our custom method defined inside method_missing. of now, have written 3 different functions handle method_missing array, range , hash separately.
you can define method_missing
enumerables opening enumerable
module , adding instance method it:
module enumerable def method_missing *args puts 'hi' end end [].hithere # => hi
but recommend define concrete sum
method (starts lower case letter, according ruby methods naming guidelines) instead of adding logic method_missing
:
module enumerable def sum # implementation end end [].sum
Comments
Post a Comment