Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll

- 2x 2x
- 1.75x 1.75x
- 1.5x 1.5x
- 1.25x 1.25x
- 1.1x 1.1x
- 1x 1x
- 0.75x 0.75x
- 0.5x 0.5x
Ruby gives us different ways to call blocks. In this video, we'll explore the yield
keyword and using block.call
.
Code Samples
This is an example of calling the block using the call
method:
def get_name(prompt, &block)
print prompt
name = gets.chomp
block.call(name)
name
end
my_name = get_name do |your_name|
puts "That's a cool name, #{your_name}!"
end
puts "my_name: #{my_name}"
The block_given?
keyword can be used to conditionally call a block if one was passed to a method:
def get_name(prompt, &block)
print prompt
name = gets.chomp
block.call(name) if block_given?
name
end
my_name = get_name("Name: ") do |your_name|
puts "That's a cool name, #{your_name}!"
end
puts "my_name: #{my_name}"
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up-
Ahmed Mohamed Fouad
11,735 Points2 Answers
-
Unsubscribed User
11,042 Points2 Answers
-
Dylan Barnard
1,860 Points2 Answers
-
Batuhan Ozgur Ozdemir
4,658 Points3 Answers
View all discussions for this video
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up