Created
July 31, 2019 22:04
-
-
Save cpkenn09y/2ef1ab357176887c11a6df82ffbd03c5 to your computer and use it in GitHub Desktop.
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
# https://mixandgo.com/learn/mastering-ruby-blocks-in-less-than-5-minutes | |
def my_method | |
puts "reached the top" | |
yield("John", 2) | |
puts "reached the bottom" | |
end | |
my_method { puts "reached yield" } | |
my_method do |name, age| | |
puts "#{name} is #{age}" | |
end | |
def my_method | |
yield("John", 2) | |
# puts "Hi #{name}" | |
end | |
my_method { |name, age| puts "#{name} is #{age} years old" } | |
#=> # "John is 2 years old" | |
#=> # "Hi John" | |
def my_method | |
value = yield("Mickey", "Mouse") | |
puts "value is #{value}" | |
end | |
my_method do |first_name, last_name| | |
"#{first_name} #{last_name}" | |
end | |
def my_map(array) | |
if block_given? | |
new_array = [] | |
for element in array | |
new_array.push yield element | |
end | |
new_array | |
else | |
raise "Requires block" | |
end | |
end | |
my_map([1, 2, 3]) do |number| | |
number * 2 | |
end | |
def wrap_in_h1 | |
"<h1>#{yield}</h1>" | |
end | |
wrap_in_h1 { "Here's my heading" } | |
wrap_in_h1 { "Ha" * 3 } | |
def wrap_in_tags(tag, text) | |
html = "<#{tag}>#{text}</#{tag}>" | |
yield html | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment