0
0
Rubyprogramming~5 mins

Block syntax (do..end and curly braces) in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a block in Ruby?
A block is a chunk of code enclosed between do..end or curly braces { } that can be passed to methods and executed.
Click to reveal answer
beginner
When should you use do..end versus curly braces { } for blocks?
do..end is usually used for multi-line blocks, while curly braces { } are preferred for single-line blocks.
Click to reveal answer
beginner
How do you pass a block to a method in Ruby?
You write the method call followed by a block using either do..end or { }. The method can then execute the block using yield.
Click to reveal answer
beginner
Example: What does this code print?<br>
3.times do
  puts "Hello"
end
It prints "Hello" three times, each on a new line.
Click to reveal answer
intermediate
Can you use both do..end and curly braces { } interchangeably?
Yes, both define blocks, but style and readability guide when to use each. Curly braces for short blocks, do..end for longer ones.
Click to reveal answer
Which block syntax is preferred for single-line blocks in Ruby?
Ado..end
Bsquare brackets []
Cparentheses ()
D{} (curly braces)
What keyword inside a method executes the passed block?
Ayield
Bcall
Cexecute
Drun
Which of these is a valid way to write a block in Ruby?
Amethod do |x| x * 2 end
Bmethod (|x| x * 2)
Cmethod { |x| x * 2 }
Dmethod [|x| x * 2]
What will this code output?<br>5.times { print "*" }
A*****
B* * * * *
C5
DError
Which block syntax is usually used for multi-line blocks?
A{} (curly braces)
Bdo..end
C() parentheses
D<> angle brackets
Explain the difference between do..end and curly braces { } when writing blocks in Ruby.
Think about block length and style.
You got /4 concepts.
    Describe how a Ruby method can use a block passed to it.
    Focus on method and block interaction.
    You got /4 concepts.