Beans (legumes) cause gas because they contain a particular sugar, which is called an oligosaccharide, that the human body can not break down fully. Oligosaccharides are large molecules and are not broken down and absorbed in the same way that other sugars are: by the normal digestive process that takes place in the small intestine. This is because the human body actually does not produce the enzyme that breaks down oligosaccharides.
Oligosaccharides make it all the way through the digestive tract to the large intestine still intact and as yet undigested. It is the bacteria that live in the large intestine that finally break down the oligosaccharides. This process is the one that produces the gas that must eventually come out of the rectum as flatulence.
By the same principal, other foods that come into the large intestine without being properly absorbed in the small intestine will cause gas. For example, stress can cause food to move through the digestive tract too quickly to be properly digested, with the end result being more gas produced in the large intestine.