class method errors:uninitialized constant

Asked 2 years ago, Updated 2 years ago, 45 views



I'm a beginner. This is my first question.
I'm sorry for the rudiments.
The class method is defined by a unique class method, but even if you execute it with the code below,
You will encounter the following error:

Code

class<<Hoge
def bar
  'bar'
end
end

Error

test.rb:4:in<main>':uninitialized constant Hoge (NameError)

I looked it up just in case, but I didn't know the cause.I am sorry to trouble you, but I would appreciate it if you could help me.

ruby

2022-09-30 20:22

1 Answers

The error indicates that Hoge has not been initialized (defined) as per the message.
So let's define Hoge.
Grammatically, Hoge doesn't have to be a class, but I think it's meant to be a class, so I wonder if the code will be as follows:

class Hoge
end
class<<Hoge
  def bar
    'bar'
  end
end

You can also write this code like this (I think this is more common):

class Hoge
  class<<self
    def bar
      'bar'
    end
  end
end


2022-09-30 20:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.