Best explanation of Ruby blocks? -
what best explanation ruby blocks can share?
both usage , writing code can take block?
i offer own explanation this answer, modified:
"blocks" in ruby not same general programming terms "code block" or "block of code".
pretend moment following (invalid) ruby code worked:
def add10( n ) puts "#{n} + 10 = #{n+10}" end def do_something_with_digits( method ) 1.upto(9) |i| method(i) end end do_something_with_digits( add10 ) #=> "1 + 10 = 11" #=> "2 + 10 = 12" ... #=> "9 + 10 = 19"
while code invalid, intent—passing code method , having method run code—is possible in ruby in variety of ways. 1 of ways "blocks".
a block in ruby very, method: can take arguments , run code those. whenever see foo{ |x,y,z| ... }
or foo |x,y,z| ... end
, blocks take 3 parameters , run ...
on them. (you might see upto
method above being passed block.)
because blocks special part of ruby syntax, every method allowed passed block. whether or not method uses block method. example:
def say_hi( name ) puts "hi, #{name}!" end say_hi("mom") puts "you suck!" end #=> hi, mom!
the method above passed block ready issue insult, since method never calls block, nice message printed. here's how call block method:
def say_hi( name ) puts "hi, #{name}!" if block_given? yield( name ) end end say_hi("mridang") |str| puts "your name has #{str.length} letters." end #=> hi, mridang! #=> name has 7 letters.
we use block_given?
see whether or not block passed along or not. in case passed argument block; it's method decide pass block. example:
def say_hi( name ) puts "hi, #{name}!" yield( name, name.reverse ) if block_given? end say_hi("mridang"){ |str1, str2| puts "is name #{str1} or #{str2}?" } #=> hi, mridang! #=> name mridang or gnadirm?
it's convention (and one, , 1 want support) classes pass instance created block.
this not exhaustive answer, not cover capturing blocks arguments, how handle arity, un-splatting in block parameters, etc. intends serve blocks-are-lambdas intro.
Comments
Post a Comment