While
counter = 1 while counter < 11 puts counter counter = counter + 1 end
Until
i = 0 until i == 6 i += 1 end puts i
For
for num in 1...10 puts num end
for numin 1...10
means "go up to but don‘t include 10." If we use two dots, this tells Ruby to include the highest number in the range.
iterator
i = 20 loop do i -= 1 print "#{i}" break if i <= 0 end
next
for i in 1..5 next if i % 2 == 0 print i end
.each iterator
object.each { |item| # Do something }
You can also use the do
keyword instead of {}
:
object.each do |item| # Do something end
The variable name between | |
can be anything you like: it‘s just a placeholder for each element of the object you‘re using .each
on.
array = [1,2,3,4,5] array.each do |x| x += 10 print "#{x}" end
.times iterator
10.times {print "haha"}
时间: 2024-10-16 22:16:33