Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created December 18, 2014 09:12
Show Gist options
  • Save Integralist/bb8760d11a03c88da151 to your computer and use it in GitHub Desktop.
Save Integralist/bb8760d11a03c88da151 to your computer and use it in GitHub Desktop.
Ruby: private class level methods
class Foo
class << self
def bar
p "im public"
end
private
def baz
p "im private"
end
end
end
Foo.bar # => im public
Foo.baz # => NoMethodError: private method `baz' called for Foo:Class
class Foo
def self.bar
p "im public"
end
private
def self.baz
p "im private"
end
end
Foo.bar # => im public
Foo.baz # => im private
@Integralist
Copy link
Author

You can get the second example (def self.baz) to work by using private_class_method :baz...

class Foo
  def self.bar
    p "im public"
  end

  def self.baz
    p "im private"
  end
  private_class_method :baz
end

Foo.bar # => im public
Foo.baz # => NoMethodError: private method `baz' called for Foo:Class

@Nakilon
Copy link

Nakilon commented Mar 28, 2019

See also https://stackoverflow.com/a/12925407/322020 and other answers there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment