0
0
Rubyprogramming~15 mins

Block given? check in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Block given? check
📖 Scenario: You are creating a simple Ruby method that behaves differently depending on whether a block is given or not. This is useful when you want to allow extra customization but also have a default behavior.
🎯 Goal: Build a Ruby method called greet that prints a default greeting if no block is given, and uses the block to customize the greeting if a block is provided.
📋 What You'll Learn
Create a method named greet
Use block_given? inside the method to check if a block is passed
Print "Hello, World!" if no block is given
If a block is given, call the block and print its result
💡 Why This Matters
🌍 Real World
Checking if a block is given allows Ruby methods to be flexible and customizable, which is common in libraries and frameworks.
💼 Career
Understanding blocks and <code>block_given?</code> is essential for Ruby developers, especially when working with Rails or writing reusable code.
Progress0 / 4 steps
1
Define the greet method
Write a method called greet with no parameters.
Ruby
Need a hint?
Use def greet to start the method and end to finish it.
2
Check if a block is given
Inside the greet method, use block_given? to check if a block is passed.
Ruby
Need a hint?
Use an if statement with block_given? inside the method.
3
Call the block or print default greeting
Inside the greet method, if a block is given, call the block with yield and print its result. Otherwise, print "Hello, World!".
Ruby
Need a hint?
Use puts yield to call and print the block result, and puts "Hello, World!" for the default.
4
Test the greet method with and without a block
Write two lines: call greet without a block, then call greet with a block that returns "Hi there!". This will show both behaviors.
Ruby
Need a hint?
Call greet alone, then call greet { "Hi there!" } to test both cases.