0
0
Rubyprogramming~10 mins

Yield to execute blocks in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to yield control to the block.

Ruby
def greet
  puts "Hello"
  [1]
  puts "Goodbye"
end
Drag options to blanks, or click blank then click option'
Areturn
Byield
Ccall
Dbreak
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'return' instead of 'yield' stops the method instead of calling the block.
Using 'call' without a block variable causes an error.
2fill in blank
medium

Complete the code to pass a value to the block using yield.

Ruby
def square(number)
  [1] number * number
end
Drag options to blanks, or click blank then click option'
Ayield
Breturn
Cyield()
Dcall
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'return' instead of 'yield' does not call the block.
Using 'yield()' without argument does not pass the value.
3fill in blank
hard

Fix the error in the method to correctly yield to the block with two arguments.

Ruby
def combine(a, b)
  [1] a, b
end
Drag options to blanks, or click blank then click option'
Ayield
Byield()
Cyield a, b
Dyield(a, b)
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'yield()' without arguments does not pass any values.
Using 'yield(a, b)' is invalid syntax in Ruby.
4fill in blank
hard

Fill both blanks to create a method that yields the square of a number and then returns a string.

Ruby
def process(number)
  result = [1] number * number
  [2] "Done"
end
Drag options to blanks, or click blank then click option'
Ayield
Breturn
Cputs
Dyield()
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'puts' instead of 'yield' does not call the block.
Not using 'return' causes the method to return the last evaluated expression.
5fill in blank
hard

Fill all three blanks to define a method that yields a greeting with a name, then yields a farewell, and finally returns a confirmation string.

Ruby
def conversation(name)
  [1] "Hello, #{name}!"
  [2] "Goodbye, #{name}!"
  [3] "Conversation finished"
end
Drag options to blanks, or click blank then click option'
Ayield
Breturn
Cyield()
Dputs
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'puts' instead of 'yield' does not call the block.
Using 'yield()' without arguments does not pass the messages.