Look at this Ruby code. What will it print?
x = 10 x = "hello" puts x
Remember, Ruby lets you change the type of a variable anytime.
In Ruby, variables can hold any type. Here, x first holds 10, then it holds "hello". So puts x prints "hello".
Why is it useful that Ruby lets you assign different types to the same variable?
Think about how much typing you save when you don't have to say the type.
Dynamic typing means you don't declare variable types. This makes writing code faster and simpler, especially for beginners or quick scripts.
What error will this Ruby code produce?
def add(a, b) a + b end puts add(5, "3")
Think about what happens when you add a number and a string in Ruby.
Ruby tries to add an Integer and a String, which is not allowed. It raises a TypeError saying the String can't be coerced into Integer.
Choose the correct Ruby method definition that accepts any type of argument and returns it.
Remember, Ruby does not require type declarations in method parameters.
Ruby methods accept any type by default. Option B is the correct syntax. Options A and B try to declare types which Ruby does not support. Option B has syntax errors.
What will this Ruby code print?
items = [1, "two", 3.0, :four] items.each do |item| case item when Integer then puts "Integer: #{item * 2}" when String then puts "String: #{item.upcase}" when Float then puts "Float: #{item / 2}" else puts "Other: #{item}" end end
Look carefully at how Ruby treats symbols and string methods.
The array has an Integer, String, Float, and a Symbol (:four). The case matches types. For the symbol, it goes to else and prints it as is, including the colon. So the output includes 'Other: :four'.