Blocks, Procs & Lambda

Ahmad hamza

What is a block?

Blocks are like nameless methods

1.times do
  puts "Hello CyRuG!"
end


1.times { puts "CyRu is Cybage Ruby Users Group" }

How blocks differ from methods

def capitalize(string) 
  puts "#{string[0].upcase}#{string[1..-1]}"
end

capitalize("salil") # prints "Salil"
capitalize("nilesh") # prints "Nilesh"

The capitalize method capitalizes a word, and we can continually invoke the capitalize method by name.

["prajakta", "trupti"].each {|string| puts "#{string[0].upcase}#{string[1..-1]}"}

# prints "Prajakta", then "Trupti"

The block that we define will only be called once and in the context of the array that we are iterating over.

Question time!!

Can anyone tell us how a method can take a block as a parameter?

deck

By Ahmad Hamza

deck

  • 498