I imagine there are any number of ways to go about inventing a gag. Perhaps you hear something which sounds ambiguous or absurd, and use that as the basis of the gag. Then with a rough idea of it, work on the punchline and perhaps modify the rest of it to make it work to best effect.
How do people here do it?