Why use nested classes in Ruby?

2

I see things like:

class Teste
    class Foo

    end

    class Bar

    end
end

Use classes within classes ... Can anyone tell me why? Is not it better and more correct to use modules?

module Teste
    class Foo

    end

    class Bar

    end
end
    
asked by anonymous 05.12.2014 / 12:06

1 answer

3

Nested classes serve 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
    
05.12.2014 / 12:25