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

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -