0
0
Rubyprogramming~20 mins

How Ruby interprets code at runtime - Practice Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Runtime Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Ruby method call and variable scope
What is the output of this Ruby code when run?
Ruby
def greet
  name = "Alice"
  puts "Hello, #{name}!"
end

greet
puts name
AHello, Alice!\nNameError: undefined local variable or method `name' for main:Object
BHello, Alice!\nAlice
CNameError: undefined local variable or method `name' for main:Object\nHello, Alice!
DHello, Alice!\nnil
Attempts:
2 left
💡 Hint
Think about where variables defined inside methods are accessible.
Predict Output
intermediate
2:00remaining
Ruby block variable behavior
What will this Ruby code output?
Ruby
x = 10
[1, 2, 3].each do |x|
  puts x
end
puts x
A1\n2\n3\n10
B10\n10\n10\n10
C1\n2\n3\n3
D1\n2\n3\nNameError
Attempts:
2 left
💡 Hint
Consider if the block variable x affects the outer x.
🔧 Debug
advanced
2:00remaining
Identify the runtime error in Ruby code
What error does this Ruby code raise when run?
Ruby
def divide(a, b)
  a / b
end

puts divide(10, 0)
ANoMethodError: undefined method `/`
BArgumentError: wrong number of arguments
CTypeError: String can't be coerced into Integer
DZeroDivisionError: divided by 0
Attempts:
2 left
💡 Hint
What happens when you divide by zero in Ruby?
🧠 Conceptual
advanced
2:00remaining
Ruby constant lookup at runtime
Given this Ruby code, what will be printed when run?
Ruby
module A
  X = 100
  class B
    X = 200
    def self.show
      puts X
    end
  end
end

A::B.show
ANameError: uninitialized constant X
B200
C100
Dnil
Attempts:
2 left
💡 Hint
Constants inside classes override outer module constants with the same name.
Predict Output
expert
2:00remaining
Ruby dynamic method definition and runtime behavior
What is the output of this Ruby code?
Ruby
class C
  define_method(:hello) do |name|
    "Hello, #{name}!"
  end
end

obj = C.new
puts obj.hello("Bob")
AArgumentError: wrong number of arguments (given 1, expected 0)
BNoMethodError: undefined method `hello' for #<C:0x0000>
CHello, Bob!
DSyntaxError: unexpected `do'
Attempts:
2 left
💡 Hint
Look at how define_method creates methods at runtime.