I've noticed that many foods, such as cabbage, garlic, and ginger, either turn blue or purple in certain conditions, or that, like purple string beans, they lose these colors when cooked. Why is this?
Anthocyanins are antioxidants that are a very common water based pigment in plants. There are over 500 varieties that have been isolated from plants which are are responsible for many blue, red, and purple pigments in flowers and fruit. It is thought that the colors serve to attract pollinators to flowers and camouflage leaves from herbivores.
They are the naturally occurring in purple snap beans, garlic, some ginger, many berries, red cabbage, as well as many other common foods. When added as a food coloring, they have the E number E163.
The color is dependent on the pH of the fluid around them. This causes many plants (such as purple beans) to lose color as they are cooked and their cell walls begin to burst and release water, diluting fluids the anthycyanins are in or absorbing cooking liquids of a different pH.
Some varieties of ginger contain anthocyanins which can turn blue when exposed to acids. Varieties of ginger originating in Japan contain these compounds, but varieties originating in China do not, which explains why this only happens to some ginger. The pH of ginger is slightly acidic, so that probably starts the reaction.
Anthocyanins are also responsible for garlic turning blue when in an acidic solution. In the case of garlic, the color is sometimes enhanced by reactions between the sulfur compounds naturally occurring in garlic and copper that may be present in water or cooking vessels. This creates another blue pigment, which is still perfectly safe to consume.
More technical information can be found in Colorants in Food.