Ruby Yield

[Solved] Ruby Yield | Perl - Code Explorer | yomemimo.com
Question : ruby yield

Answered by : mateusz-drewniak

# yield calls a passed block (anonymous function) passed to the method
def some_method puts "Before caling the block" yield puts "After calling the block"
end
# if a method yields and there was no block
# an error is raised
some_method #=> no block given (yield) (LocalJumpError)
# Here is a shortened syntax of passing a block
some_method { puts "Hello from the block" }
#=> Before caling the block
#=> Hello from the block
#=> After caling the block
# Here is the longer syntax of passing a block
some_method do puts "Hello from the block"
end
# You can use the `block_given?` method to
# determine whether a block is present
def method_with_optional_block puts "Before caling the block" yield if block_given? puts "After calling the block"
end
# No error is raised when no block has been passed
method_with_optional_block
#=> Before caling the block
#=> After caling the block
method_with_optional_block { puts "Hello" }
#=> Before caling the block
#=> Hello
#=> After caling the block
# You can also capture the block as a `Proc`
def method_with_proc_block(&block) # same thing as `yield if block_given?` block.call if block # You can forward the passed block to another method some_method(&block)
end 

Source : | Last Update : Sat, 06 Aug 22

Answers related to ruby yield

Code Explorer Popular Question For Perl