Consider the following Ruby code. What will it print?
def greet(name) puts "Hello, #{name.capitalize}!" end greet("alice")
Look at the capitalize method and how it changes the string.
The capitalize method makes the first letter uppercase and the rest lowercase. So "alice" becomes "Alice".
According to Ruby style guide essentials, which method name style is preferred?
Think about how Ruby methods are usually named to improve readability.
Ruby style guide recommends using snake_case for method names for clarity and consistency.
Examine the code below. What error will it raise when run?
numbers = [1, 2, 3] puts numbers[3].to_s
What does Ruby return when accessing an array index that is out of range?
Accessing an out-of-range index returns nil. Calling to_s on nil returns an empty string, so no error occurs.
Choose the correct Ruby syntax for defining a class Person with an initialize method that takes a name parameter.
Remember Ruby uses def and end to define methods and classes, and instance variables start with @.
Option A correctly defines the class and initialize method, assigns the parameter to an instance variable, and closes all blocks properly.
What is the number of key-value pairs in the hash created by this Ruby code?
hash = { a: 1, b: 2, a: 3, c: 4 }Consider what happens when a hash has duplicate keys.
In Ruby, if a hash has duplicate keys, the last value for that key overwrites previous ones. So keys are :a, :b, :c with values 3, 2, 4 respectively, total 3 pairs.