Ruby - Pass code block as variable

Introduction

You can write methods of your own to handle code blocks. For example:

Demo

def each_vowel(&code_block) 
 %w{a e i o u}.each { |vowel| code_block.call(vowel) } 
end # from  w  ww.ja v  a 2 s.  co m

each_vowel { |vowel| puts vowel }

Result

each_vowel is a method that accepts a code block.

The code block is marked by ampersand (&) before the variable name code_block in the method definition.

It then iterates over each vowel in the literal array %w{a e i o u} and uses the call method on code_block to execute the code block once for each vowel.

You can use the yield method to detect any passed code block:

Demo

def each_vowel 
 %w{a e i o u}.each { |vowel| yield vowel } 
end # from   w  w  w . ja  va  2 s .  c  o m

each_vowel { |vowel| puts vowel }

Result

Related Topics