The ratio between atoms forming a specific compound can be any whole number ratio. For instance, the ratio of hydrogen to oxygen in water is always 2:1, giving us H2O.
The reason atoms combine in whole number ratios is because of the way the atoms join to create a compound. When an atom has an incomplete valence (outer) shell of electrons, it will combine with other atoms in a way that completes that outer shell, usually with 8 electrons. For instance, the element Sodium has just one valence electron, so it will bond with elements like Chlorine, which has 7 valence electrons. Sodium's single electron is transferred to the Chlorine atom, and the Compound NaCl is formed, which always has a 1:1 ratio of Sodium to Chlorine.
However Magnesium has two valence electrons. If Magnesium is to bond with Chlorine, it cannot be in a 1:1 ratio, because a single Chlorine cannot take in both of the Magnesium's valence electrons. So instead a single Magnesium atom will bond with two Chlorines, sharing one of its valence electrons with each, and creating the compound MgCl2, with a 1:2 ratio.