Why use nested classes in Ruby?

Asked

Viewed 64 times

2

Back and forth I see things like:

class Teste
    class Foo

    end

    class Bar

    end
end

Using classes within classes... Can anyone tell me what this is for? It’s not better and more correct to use modules?

module Teste
    class Foo

    end

    class Bar

    end
end

1 answer

3


Nested classes are for when you need a class that does not need or should not be accessible outside the context of another class.

class Comunidade
  class Pessoa
    def diga_ola
      'Olá!'
    end
  end

  def alguem_diga_ola
    joao = Pessoa.new
    joao.diga_ola
  end
end

Comunidade.new.alguem_diga_ola # Olá!
Pessoa.new.diga_ola # NameError: Unitialized constant Pessoa
  • 1

    is very common in dynamic languages, in python also happens a lot.

  • 1

    Nested classes are great for refactoring complex classes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.