I was recently quite surprised to find that top-level “functions” are
actually private instance methods of Object, for I really expected them to be
singleton methods (see http://www.ruby-talk.com/blade/57607). This seemed
“unclean” to me from the beginning, because I saw that this would mean
that all Ruby objects were getting strange private methods, but OTOH
nothing seemed to be wrong as the public interface was not modified,
and these methods were shadowed by new ones.
However this feeling simply didn’t go away and I finally found one
(admittedly contrived) case where this could bite.
The following code is stupid for several reasons, but it’s probably not
the only one that illustrates the point I’m trying to make
batsman@tux-chan:/tmp$ cat b.rb
class A
def hello
“A#hello”
end
end
class Proxy
def initialize(obj)
@obj = obj
end
def method_missing(id, *args)
@obj.send id, *args
end
def wtf?
p "Right: #{hello == "A#hello"}"
end
end
o = Proxy.new(A.new)
o.wtf?
def hello
p “Top level”
end
o.wtf?
batsman@tux-chan:/tmp$ ruby b.rb
“Right: true”
“Top level”
“Right: false”
This wouldn’t happen if “functions” were singleton methods of the
top-level object. But I see that then they’d only work with that
‘self’. And having them as class methods of Object would require an
explicit “Object.” before each call.
The question is “has anybody ever been bitten by such a thing?”.
I understand why things are the way they’re, but I’d like to know if
this is a real issue or not to “calibrate” my “uncleanness detector”.
It kinda frightens me that an innocent ‘def function … end’ can break
objects much lower in the hierarchy without any warning. But this could
simply be taken as yet another reason to forget about “functions” and/or
use namespaces.
Perhaps on a more philosophical side: “is the interface of a class
defined by what it doesn’t support, too?” (although not really connected
to this) and “is it OK for an object to depend on itself not supporting
some message”?
···
–
_ _
__ __ | | ___ _ __ ___ __ _ _ __
'_ \ /| __/ __| '_
_ \ / ` | ’ \
) | (| | |__ \ | | | | | (| | | | |
.__/ _,|_|/| || ||_,|| |_|
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com
If loving linux is wrong, I dont wanna be right.
– Topic for #LinuxGER