Bird
0
0

You want to write a Ruby method that adds two values but safely handles if one is a string representing a number. Which approach best uses Ruby's dynamic and strong typing?

hard📝 Application Q15 of 15
Ruby - Variables and Data Types
You want to write a Ruby method that adds two values but safely handles if one is a string representing a number. Which approach best uses Ruby's dynamic and strong typing?
AConvert both to strings and concatenate.
BAdd values directly without conversion.
CConvert both to integers before adding using to_i method.
DUse static type declarations for parameters.
Step-by-Step Solution
Solution:
  1. Step 1: Understand dynamic typing flexibility

    Ruby variables can hold any type, so inputs can be string or integer.
  2. Step 2: Use strong typing safety

    To avoid TypeError, convert strings to integers explicitly before adding.
  3. Step 3: Evaluate options

    Converting both to integers using to_i before adding is safe. Adding directly risks TypeError. Static type declarations are invalid in Ruby. Converting to strings performs concatenation instead of addition.
  4. Final Answer:

    Convert both to integers before adding using to_i method. -> Option C
  5. Quick Check:

    Dynamic + Strong typing = explicit conversion [OK]
Quick Trick: Convert strings to numbers before math to avoid errors [OK]
Common Mistakes:
MISTAKES
  • Ignoring type conversion before arithmetic
  • Assuming Ruby auto-converts types
  • Using static typing syntax in Ruby

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes