Ruby Class#New - Why Is 'New' a Private Method

Ruby Class#new - Why is `new` a private method?

As I recall, Matrix is a purely functional class; its objects are immutable, and simply creating a new Matrix object is normally useless as the API doesn't have any mutable operations.

So, new Matrix objects are created by an API that just doesn't use new at the user level.

It's a design decision made by the author.

Update: OIC, you had no intention of using the standard library Matrix class. So the above is technically the reason for your problem but it would have been more helpful for me to just say:

Your definition of Matrix is clashing with the Ruby Standard
Library class of the same name.

New instances from instance methods when Class.new is private

You can always use send to get around the access control:

def from_x arg
stuff_from_arg = arg.something #something meaningful from arg
self.class.send(:new, stuff_from_arg)
end

Private class (not class method) in a Ruby module?

I haven't seen such concept so far in Ruby, but I guess you could simulate that by creating private method which would return a class created as a local variable (remember that in Ruby, a class is an object just like any other, and can be instantiated in a method and returned by it).

BTW, even private methods in Ruby aren't as private as in other languages - you can always access them using send method. But doing that implies you know what you are doing.

Why is attr_accessor making my methods private?

As described in the examples from the documentation, Class.new is passed a block, so I would do as below:

klass = Class.new do
attr_accessor :name
end

instance = klass.new
instance.name = "Foo"
instance.name #=> "Foo"

Private module methods in Ruby

I think the best way (and mostly how existing libs are written) to do this is by creating a class within the module that deals with all the logic, and the module just provides a convenient method, e.g.

module GTranslate
class Translator
def perform(text)
translate(text)
end

private

def translate(text)
# do some private stuff here
end
end

def self.translate(text)
t = Translator.new
t.perform(text)
end
end

What is Class.new?

According to the documentation, Class.new

Creates a new anonymous (unnamed) class with the given superclass (or Object if no parameter is given).

Furthermore,

You can give a class a name by assigning the class object to a constant.

Sheep is that constant, so your code is equivalent to:

module Fence 
class Sheep
def speak
"Bah."
end
end
end


Related Topics



Leave a reply



Submit