I am little bit curious about to know that, is there any difference between below two approaches?
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
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With