Ruby on rails 为什么可以';self.method';不在同一类中使用方法?

Ruby on rails 为什么可以';self.method';不在同一类中使用方法?,ruby-on-rails,ruby,Ruby On Rails,Ruby,为什么当我从一个类中执行self.method时,我会为MyModule::MyThermodule::MyClass:class获得一个未定义的方法“my_method” module MyModule module OtherModule class MyClass < Base def my_method end def self.my_self_method my_method end end end end 我不明白。在您的代码

为什么当我从一个类中执行
self.method
时,我会为MyModule::MyThermodule::MyClass:class获得一个
未定义的方法“my_method”

module MyModule
 module OtherModule
  class MyClass < Base

   def my_method
   end

   def self.my_self_method
    my_method
   end

  end
 end
end

我不明白。

在您的代码中,您定义了一个实例方法(
my\u method
)和一个类方法(
my\u self\u method

这意味着您可以拨打:

MyClass.my_self_method

如果希望从
my_self_method
调用
my_method
,可以将其定义为:

def self.my_method
  ...
end
然后将提供以下信息:

def self.my_self_method
  my_method
end
这是另一种选择。有一条评论指出,从类方法中调用
new.my_方法
是一种不好的做法,但我发现有一种模式应用了这一点,我觉得非常惯用,例如:

class MyClass
  def self.run(the_variables)
    new(the_variables).process
  end

  def initialize(the_variables)
    # setup the_variables
  end

  def process
    # do whatever's needed
  end
end
这允许一个简单的入口点
MyClass.run(变量)
。如果您的用例看起来合适,那么类似的模式将是:

module MyModule
  module OtherModule
    class MyClass < Base

      def my_method
      end

      def self.my_self_method
        new.my_method
      end
    end
  end
end
模块MyModule
模块其他模块
类MyClass
我肯定有不同意这种模式的余地,我很想在评论中听到其他人的意见


希望这有助于澄清@N.Safi中的一些问题。

在您的代码中,您定义了一个实例方法(
my\u method
)和一个类方法(
my\u self\u method

这意味着您可以拨打:

MyClass.my_self_method

如果希望从
my_self_method
调用
my_method
,可以将其定义为:

def self.my_method
  ...
end
然后将提供以下信息:

def self.my_self_method
  my_method
end
这是另一种选择。有一条评论指出,从类方法中调用
new.my_方法
是一种不好的做法,但我发现有一种模式应用了这一点,我觉得非常惯用,例如:

class MyClass
  def self.run(the_variables)
    new(the_variables).process
  end

  def initialize(the_variables)
    # setup the_variables
  end

  def process
    # do whatever's needed
  end
end
这允许一个简单的入口点
MyClass.run(变量)
。如果您的用例看起来合适,那么类似的模式将是:

module MyModule
  module OtherModule
    class MyClass < Base

      def my_method
      end

      def self.my_self_method
        new.my_method
      end
    end
  end
end
模块MyModule
模块其他模块
类MyClass
我肯定有不同意这种模式的余地,我很想在评论中听到其他人的意见


希望这有助于澄清@N.Safi.

中的一些问题,因为
myu-self\u方法中的
self
MyClass
class,而不是
MyClass
实例。谢谢,所以不可能调用
myu-method
?不可能从类方法范围调用实例方法。您可以在类方法内创建实例,然后对其调用方法:
new.my\u method
。但是如果你必须做这样的事情,那就是因为这是一个糟糕的代码。因为
self
myu-self\u方法中
MyClass
类,而不是
MyClass
实例。谢谢,那么不可能调用
myu-method
吗?不可能从类方法范围调用实例方法。您可以在类方法内创建实例,然后对其调用方法:
new.my\u method
。但是如果你必须做这些事情,那就是说这是一个糟糕的代码。这对@N.Safi有帮助吗?这对@N.Safi有帮助吗?