to do something surprising
You didn't know how the story would end and then the author pulled a rabbit out of her hat, and it all made sense. Usage notes: sometimes used to describe a surprising solution to a problem: The governor pulled a rabbit out of a hat by putting together a budget without increasing taxes.