Matt Schuchard Matt Schuchard - 2 months ago 5
Ruby Question

Ruby incorrectly interpreting class namespace

I have code that looks like the following snippet:

require_relative 'class/foo'
require_relative 'class/bar'
require_relative 'class/baz'

class MyClass
def initialize(arg)
...

%w(wordone wordtwo).each do |word|
Foo.public_send(word.to_sym, arg)
Bar.public_send(word.to_sym, arg)
Baz.public_send(word.to_sym, arg)
end
end
end


In each of those three requires is code like this template:

class Foo
def self.wordone(arg)
# do stuff
end

def self.wordtwo(arg)
# do stuff
end
end


This works perfectly fine for
Foo
and
Bar
, but once it hits
Baz
:

NameError: uninitialized constant MyClass::Baz
Did you mean? Baz


I clearly specified
Baz
and not
MyClass::Baz
. Why is Ruby randomly misinterpreting the namespace for the third object method invocation and not the first two?

I should also mention that if I change:

Baz.public_send(word.to_sym, arg)


to:

Baz.wordone(arg)


then it works perfectly for that one method invocation, but I obviously need to loop over multiple method invocations for that class. So Ruby's namespace misinterpretation seems to be linked to the use of
public_send
on the object method.

This is occurring on Ruby 2.3.1p112.

mwp mwp
Answer

Codifying my (apparently helpful) comment from the OP:

Basically what's happening here is Ruby can't find class Baz at the top-level, so it's looking under MyClass (it actually tries looking under MyClass first, then checks the top-level; the error message tells you that it couldn't find it in either namespace).

Comments