I was wondering how to access a global function fn in ruby from a class which also defined a method fn. I have made a workaround by aliasing the function like so:
def fn
end
class Bar
alias global_fn fn
def fn
# how to access the global fn here without the alias
global_fn
end
end
I’m looking for something along the lines of c++’s :: to access global scope but I can’t seem to locate any information about it. I guess I don’t know specifically what I’m looking for.
At the top-level a
defadds a private method toObject.I can think of three ways to get the top-level function:
(1) Use
sendto invoke the private method onObjectitself (only works if the method is not a mutator sinceObjectwill be the receiver)(2) Get a
Methodinstance of the top-level method and bind it to the instance you want to invoke it on:(3) Use
super(assumes no super classes ofBarbelowObjectredefine the function)UPDATE:
Since solution (2) is the preferable one (in my opinion) we can try to improve the syntax by defining a utility method on
Objectcalledsuper_method:Use like the following:
Where the first argument to
super_methodmust be a valid superclass ofBar, the second argument the method you want to invoke, and all remaining arguments (if any) are passed along as parameters to the selected method.