To use self. or not.. in Rails

后端 未结 6 553
长情又很酷
长情又很酷 2020-11-30 21:29

I\'ve been coding in Ruby for sometime now, but I don\'t understand when to use:

def self.METHOD_NAME
end

or just:

def METH         


        
6条回答
  •  悲&欢浪女
    2020-11-30 22:23

    In this context - def self.method_name makes it sort of equivalent to the Java static method:

    ruby:

    class HexHelper
      def self.to_h(num)
        sprintf("%x", num)
      end
    end
    
    use: HexHelper.to_h(12345)
    

    java:

    public class HexHelper
    {
      public static String toHex(int num)
      {
        return new PrintfFormat("%x").sprintf(num);
      }
    }
    
    use: HexHelper.toHex(12345)
    

提交回复
热议问题