Spoilers follow, and this is from the books (not the movies)...
In The Chamber of Secrets:
Harry retrieves Goderic Gryffindor's sword from the sorting hat during the confrontation with the basilisk. After this Dumbledore keeps hold of the sword in a glass case in his office.
Then in The Deathly Hallows:
Harry and Ron do a deal with Griphook to return Gryffindor's sword to the goblins after they have retrieved Hufflepuff's cup, planning to partially double cross him by holding on to it until all the horcruxes have been destroyed. However Griphook double crosses them first, and keeps hold of the sword.
Then, in the battle at the end of the book:
Voldemort puts the sorting hat on Neville Longbottom's head and sets him on fire. Instead of burning Neville pulls Gryffindor's sword out of the sorting hat and beheads Nagini, destroying Voldemort's last horcrux.
However, if the sword could always be pulled out of the hat by someone sufficiently heroic then why the need to:
Create a copy of the sword to fool Bellatrix Lestrange into thinking she had the real one in Gringott's vault? Why forge a copy and risk Snape placing it in the lake if it could always have been pulled from the sorting hat, regardless of where it was or how it was protected?
How was Gryffindor's sword pulled from the hat the second time? Surely it was beyond the reach of accio or any other charms once returned to its goblin creators?