ruby - Add method to base class in the context of module -



ruby - Add method to base class in the context of module -

i want add together custom method string class in ruby. aware can done next code:

class string def my_own_method # impelementation comes here end end

if write code in file "string.rb" , somewhere else i.e. in irb, write require "string" works quite fine , have access custom method on string object. however, problem arises when want bundle custom code module this:

module class string def my_own_method # implementation end end end

then when include module (with no error), don't have access method on each string object unless instantiate straight string calling, say,s = a::string.new. in case have access custom method s variable not on string object. shall both bundle util classes , automatically add together methods base of operations classes? help appreciated.

one alternative utilize :: ensure grabbing top-level string class:

module class ::string def my_own_method self.reverse end end end "some string".my_own_method # => "gnirts emos"

i have agree sergio's point @ end of answer. not sure of need this.

ruby metaprogramming

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -