In Ruby, I can create global methods 2 ways as far as I know. One is inside `Kernel` module or inside the `Obect` class.
···
#######
# Object
#######
class MyComplex
def initialize( real, image )
"#{real} + #{image}i"
end
end
def MyComplex( real, image )
MyComplex.new real, image
end
class Klass < BasicObject
def create_object a, b
MyComplex(a, b)
end
end
p Klass.new.create_object 1, 2
# in `create_object': undefined method `MyComplex' for #<Klass:0x94ef7d8> (NoMethodError)
#######
# Kernel
#######
class MyComplex
def initialize( real, image )
"#{real} + #{image}i"
end
end
module Kernel
def MyComplex( real, image )
MyComplex.new real, image
end
end
class Klass < BasicObject
include ::Kernel
def create_object a, b
MyComplex(a, b)
end
end
p Klass.new.create_object 1, 2
# >> #<MyComplex:0x8b2b260>
Only one difference I can see, if I put it inside the `Kernel`, I can then use it inside the class, which doesn't have `Object` in ancestor chains( via the _mixin_) as well as which have Object(as Ruby mixed the Kernel module by itself). But if I define it inside the `Object`, then classes which has `Object` in there ancestor chain can use the MyComplex method only, otherwise not.
As per you which practice is the best practice and why ? Any other reasons to choose the either approach ?
--
Regards,
Arup Rakshit
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan