Last active
April 2, 2019 20:37
-
-
Save Sihui/5ccb41f46a4cbafa2b19f40670042393 to your computer and use it in GitHub Desktop.
For [Code Block, Proc, Lambda, and Closure in Ruby]()
This file contains 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
# Code Block | |
#1. {} Mostly used as a one-liner | |
{ puts 'Hi' } | |
#2. do end | |
do | |
puts 'Hi' | |
end | |
# example: arguments are wrapped between || | |
[1, 2].map {|num| num * 2} | |
# Proc | |
#1. Proc.new followed by a code block | |
Proc.new { puts 'Hi' } | |
Proc.new do | |
puts 'Hi' | |
end | |
#2. proc followed by a code block | |
proc { puts 'Hi' } | |
proc do | |
puts 'Hi' | |
end | |
# example: arguments are wrapped between || | |
times_2 = proc { |num| num * 2 } | |
# Lambda | |
# 1. lambda followed by a code block | |
lambda { puts 'Hi' } | |
lambda do | |
puts 'Hi' | |
end | |
#2. -> (stabby lambda) | |
-> { puts 'Hi' } | |
-> do | |
puts 'Hi' | |
end | |
#example: -> takes argument outside of {} | |
times_2 = -> (num) { num * 2 } | |
# Only -> takes argument outside of {} | |
->(arg) { puts arg } | |
# The rest takes argument in between || | |
{ |arg| puts arg } | |
proc do |arg| | |
puts arg | |
end | |
lambda { |arg| puts arg } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment