Rasefon
Rasefon

Reputation: 11

What is the meaning of defined a method by using :: operator in Ruby?

For example:

class A
   def A::f
   end
end

What is A::f ? I suppose it is neither class method nor instance method...

Upvotes: 1

Views: 211

Answers (2)

Mike Bethany
Mike Bethany

Reputation:

Using the double colons creates a class method. You can see this by doing a simple test:

class A 
  def A::f 
    puts "Called A::f"
  end 
end

puts "A.public_methods:"
puts A.public_methods(false)
puts

a = A.new

puts "a.public_methods:"
puts a.public_methods(false)
puts

puts "Attempt to call f"
A.f
a.f

Output:

A.public_methods:
f
allocate
new
superclass

a.public_methods:

Attempt to call f
Called A::f
NoMethodError: undefined method ‘f’ for #<A:0x0000010084f020>

Upvotes: 3

Related Questions