Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails定义方法的不同方式_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails rails定义方法的不同方式

Ruby on rails rails定义方法的不同方式,ruby-on-rails,ruby,Ruby On Rails,Ruby,到目前为止,我学习Rails的时间不长。。。。因此,如果有任何问题,请随时纠正我 我看到在rails中定义方法有两种方式 def方法名称(参数) def self.method\u name(参数) 区别(据我所知)在于1主要用于控制器,而2用于模型。。。但有时我会在模型中遇到定义为1的方法 你能给我解释一下这两种方法的主要区别吗。这定义了可在模型实例中使用的实例方法。 2号。这定义了一个类方法,并且只能由类本身使用。 例如: 方法self.method_名称定义类上的方法。基本上,在类定义中,

到目前为止,我学习Rails的时间不长。。。。因此,如果有任何问题,请随时纠正我

我看到在rails中定义方法有两种方式

  • def方法名称(参数)
  • def self.method\u name(参数)
  • 区别(据我所知)在于1主要用于控制器,而2用于模型。。。但有时我会在模型中遇到定义为1的方法


    你能给我解释一下这两种方法的主要区别吗。这定义了可在模型实例中使用的
    实例方法。
    2号。这定义了一个
    类方法
    ,并且只能由类本身使用。
    例如:


    方法self.method_名称定义类上的方法。基本上,在类定义中,将self视为所定义的类。因此,当您说def self.method_name时,您是在类本身上定义方法

    class Foo 
      def method_name(param)
         puts "Instance: #{param}"
      end
    
      def self.method_name(param)
         puts "Class: #{param}"
      end
    end
    
    > Foo.new.method_name("bar")
    Instance: bar
    > Foo.method_name("bar")
    Class: bar
    
    class Foo 
      def method_name(param)
         puts "Instance: #{param}"
      end
    
      def self.method_name(param)
         puts "Class: #{param}"
      end
    end
    
    > Foo.new.method_name("bar")
    Instance: bar
    > Foo.method_name("bar")
    Class: bar