Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between Ruby class method calling with in class method with and without self?

Tags:

ruby

I am little bit curious about to know that, is there any difference between below two approaches?

  1. Calling class method with in class method using self

    class Test
      def self.foo
       puts 'Welcome to ruby'
      end
    
     def self.bar
      self.foo
     end
    
    end
    

    Test.bar # Welcome to ruby

  2. Calling class method with in class method without self

    class Test
      def self.foo
       puts 'Welcome to ruby'
      end
    
     def self.bar
      foo
     end
    
    end
    

    Test.bar # Welcome to ruby

like image 327
Engr. Hasanuzzaman Sumon Avatar asked Apr 17 '15 07:04

Engr. Hasanuzzaman Sumon


1 Answers

Yes, there is a difference. But not in your example. But if foo was a private class method, then your first version would raise an exception, because you call foo with an explicit receiver:

class Test
  def self.foo
    puts 'Welcome to ruby'
  end
  private_class_method :foo

  def self.bar
    self.foo
  end
end

Test.bar
#=> NoMethodError: private method `foo' called for Test:Class

But the second version would still work:

class Test
  def self.foo
    puts 'Welcome to ruby'
  end
  private_class_method :foo

  def self.bar
    foo
  end
end

Test.bar
#=> "Welcome to ruby"
like image 134
spickermann Avatar answered Nov 20 '22 22:11

spickermann