Thuta Learning
IntermediateProgrammingbeginner

Iterators (.each)

Relax. We'll talk through this in plain words — no textbook voice.

Iterators are hugely important in idiomatic Ruby code. .each, .map, and .select let you work with items in an array or hash in a way that's readable and clear.

ruby
prices = [100, 250, 400]

prices.each do |price|
  puts "Price: #{price} yen"
end

tax_included = prices.map do |price|
  price * 1.1
end

puts tax_included

each runs a block once for every item. map transforms each item and returns a brand-new array.

You should see
Price: 100 yen Price: 250 yen Price: 400 yen 110.00000000000001 275.0 440.00000000000006

Info

A handy rule of thumb: reach for map when you want new data back, and each when you just want to produce output.

Easy traps

  • Float precision can cause issues with money calculations. In real payment systems, it's better to store amounts like yen or cents as integers.
Iterators (.each) | Thuta Learning