Gandalf is one of the lesser gods of creation, the [Maiar](https://en.wikipedia.org/wiki/Maia_(Middle-earth)), what he does and doesn't know is never made clear but as a servant of [Eru Ilúvatar](https://en.wikipedia.org/wiki/Eru_Il%C3%BAvatar) his power in Arda is almost limitless, although the restraints placed on it's use are almost total, but his knowledge base is unavoidably huge. He arrives in Middle-Earth *after* the fall of Númenor to Sauron's machinations and the sealing off of the utmost west, therefore he knows the history of the One Ring (I seem to recall that he's one of the Maiar who is actually *there* when Númenor goes down in ruin, or just before, but I could be wrong). He actually knows more about the Ring than he does about Middle-Earth, he's not native to the world we see him in when we read *The Lord of the Rings*. There's a lot about this in the appendices at the end of *The Lord of the Rings*, more of it, in particular the origins of the Wizards, is in *The Book of Lost Tales* under Istari but most of it is in *The Silmarillion*, particularly the fall of Númenor, which is a heavy read to say the least but worthwhile if you actually want to understand the world of Tolkien.