Last active
July 5, 2020 06:15
-
-
Save SyunWatanabe/2754ec63aa141519c506011fa6e70a91 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # frozen_string_literal: true | |
| # block | |
| # simple | |
| def say_fact | |
| if block_given? | |
| puts 'i got block' | |
| else | |
| puts 'i need block' | |
| end | |
| end | |
| say_fact # => i need block | |
| say_fact { 'block' } # => i got block | |
| # yield pass arg | |
| def yield_pass_arg | |
| yield('Thank you given me block') | |
| rescue StandardError => e | |
| puts e.message | |
| puts 'give me block' | |
| end | |
| yield_pass_arg # => no block given (yield), give me block | |
| yield_pass_arg { |given| puts given } # => Thank you given me block | |
| # Proc | |
| # block to proc | |
| def wait_for_block(&proc) | |
| p proc | |
| proc.call | |
| end | |
| wait_for_block { puts 'Proc is very handy' } # => Proc is very handy | |
| # lambda | |
| def give_me_lambda | |
| proc1 = -> { puts 'made by lambda' } | |
| proc2 = ->(greeting) { puts greeting } | |
| proc1.call | |
| proc2.call('how are you?') | |
| end | |
| give_me_lambda # => made by lambda, how are you? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment