Ruby - Using block in each method

Introduction

The following code uses do..end blocks to iterate over ranges like this:

Demo

(1..3).each do |i|
    puts(i)
end

Result

You can use do..end blocks to iterate over arrays:

Demo

arr = ['one','two','three','four']
arr.each do |s|# from   ww  w  .  ja v a2  s. c  o  m
    puts(s)
end

Result

You can execute a block repeatedly by passing it to the loop method:

Demo

i=0
arr = ['one','two','three','four']
loop {# from   w  w  w. jav a  2 s  .c o  m
   puts(arr[i])
   i+=1
   if (i == arr.length) then
       break
   end
}

Result

Related Topic