Bird
0
0

Given str = "abracadabra", which code extracts every second character starting from index 0 to index 8 (inclusive)?

hard📝 Application Q15 of 15
Ruby - String Operations
Given str = "abracadabra", which code extracts every second character starting from index 0 to index 8 (inclusive)?
Astr[0..8][::2]
Bstr[0..8].chars.select.with_index { |_, i| i.even? }.join
Cstr[0, 8, 2]
Dstr[0..8].chars.each_slice(2).map(&:first).join
Step-by-Step Solution
Solution:
  1. Step 1: Understand Ruby slicing limitations

    Ruby's slice method does not support step values like Python. So str[0, 8, 2] or str[0..8][::2] are invalid.
  2. Step 2: Use chars with index filtering to pick every second character

    str[0..8] gets substring 'abracadab'. Then chars.select.with_index { |_, i| i.even? } picks characters at even indices: a (0), r (2), c (4), d (6), b (8). Joining gives 'ar cdb' without spaces: 'arcdb'.
  3. Final Answer:

    str[0..8].chars.select.with_index { |_, i| i.even? }.join -> Option B
  4. Quick Check:

    Use chars and select.with_index for stepping [OK]
Quick Trick: Ruby slice has no step; use chars with index filtering [OK]
Common Mistakes:
MISTAKES
  • Trying Python-style slicing with step
  • Using invalid slice parameters
  • Not converting string to chars before filtering

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes