Methotrexate works by inhibiting the enzyme dihydrofolate reductase, which is crucial for DNA synthesis and cell replication. This action makes it effective in targeting rapidly dividing cells, such as those found in cancerous tissues and early pregnancy tissue in the case of an ectopic pregnancy.