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 w ww . ja  va2  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  ww  . j  a  v  a2 s .  c om
   puts(arr[i])
   i+=1
   if (i == arr.length) then
       break
   end
}

Result

Related Topic