Bird
Raised Fist0
Rubyprogramming~10 mins

String slicing and indexing in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - String slicing and indexing
Start with a string
↓
Choose index or range
↓
Extract character(s)
↓
Return substring or character
↓
Use result or end
This flow shows how Ruby takes a string, uses an index or range to slice, and returns the selected part.
Execution Sample
Ruby
str = "hello"
char = str[1]
slice = str[1..3]
puts char
puts slice
This code extracts a single character and a substring from 'hello' and prints them.
Execution Table
StepExpressionEvaluationResultExplanation
1str = "hello"Assign string"hello"Variable str now holds 'hello'
2char = str[1]Index 1"e"Second character is 'e' (indexing starts at 0)
3slice = str[1..3]Range 1 to 3"ell"Substring from index 1 to 3 inclusive is 'ell'
4puts charPrint chareOutputs 'e' to console
5puts slicePrint sliceellOutputs 'ell' to console
6EndNo more codeExecution stopsProgram ends after printing
💡 All code lines executed; program ends normally.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
strnil"hello""hello""hello""hello"
charnilnil"e""e""e"
slicenilnilnil"ell""ell"
Key Moments - 2 Insights
Why does str[1] return 'e' and not 'h'?
Ruby strings start indexing at 0, so str[0] is 'h' and str[1] is the next character 'e'. See execution_table row 2.
What does str[1..3] include exactly?
The range 1..3 includes indexes 1, 2, and 3, so it extracts characters at those positions: 'e', 'l', and 'l'. See execution_table row 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of char after step 2?
A"e"
B"h"
C"l"
D"o"
💡 Hint
Check execution_table row 2 under Result column.
At which step does the variable slice get its value?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table rows and see when slice is assigned.
If we change str[1..3] to str[2..4], what would slice be?
A"ell"
B"llo"
C"hel"
D"lo"
💡 Hint
Check variable_tracker for slice and think about indexes 2 to 4 in 'hello'.
Concept Snapshot
Ruby strings use zero-based indexing.
Use str[index] to get one character.
Use str[start..end] to get substring including end.
Negative indexes count from end.
Out-of-range indexes return nil.
Slicing returns a new string.
Full Transcript
This example shows how Ruby strings can be sliced and indexed. We start with a string 'hello'. Using str[1] gets the character at index 1, which is 'e' because indexing starts at zero. Using str[1..3] extracts characters from index 1 to 3 inclusive, resulting in 'ell'. The program prints these values. Variables str, char, and slice change as the code runs. Understanding zero-based indexing and inclusive ranges helps avoid confusion. The execution table and variable tracker show each step clearly.

Practice

(1/5)
1. In Ruby, what does str[0] return when str = "hello"?
easy
A. The first character of the string, 'h'
B. The entire string 'hello'
C. The last character of the string, 'o'
D. An error because indexing starts at 1

Solution

  1. Step 1: Understand Ruby string indexing

    Ruby strings are indexed starting at 0, so the first character is at index 0.
  2. Step 2: Apply indexing to the string 'hello'

    Accessing str[0] returns the first character 'h'.
  3. Final Answer:

    The first character of the string, 'h' -> Option A
  4. Quick Check:

    Index 0 = 'h' [OK]
Hint: Remember Ruby indexes start at zero for strings [OK]
Common Mistakes:
  • Thinking indexing starts at 1
  • Expecting the whole string instead of one character
  • Confusing last character with first
2. Which of the following is the correct way to get the substring 'ell' from str = "hello" using slicing?
easy
A. str[1,3]
B. str[0,3]
C. str[2..4]
D. str[1...3]

Solution

  1. Step 1: Understand slicing syntax

    In Ruby, str[start, length] extracts a substring starting at start with length characters.
  2. Step 2: Extract 'ell' from 'hello'

    'ell' starts at index 1 and has length 3, so str[1,3] returns 'ell'.
  3. Final Answer:

    str[1,3] -> Option A
  4. Quick Check:

    Substring from index 1, length 3 = 'ell' [OK]
Hint: Use [start, length] to slice substrings easily [OK]
Common Mistakes:
  • Using range with wrong end index
  • Confusing start and length parameters
  • Using negative indices incorrectly
3. What is the output of this Ruby code?
str = "programming"
puts str[-4, 3]
medium
A. ing
B. ram
C. amm
D. min

Solution

  1. Step 1: Understand negative indexing and slicing

    Negative index -4 means counting from the end: 'g'( -1), 'n'( -2), 'i'( -3), 'm'( -4). So index -4 points to 'm'.
  2. Step 2: Extract substring starting at 'm' with length 3

    From 'm' take 3 characters: 'm', 'i', 'n' forming 'min'.
  3. Final Answer:

    min -> Option D
  4. Quick Check:

    str[-4,3] = 'min' [OK]
Hint: Negative index counts from end; length slices forward [OK]
Common Mistakes:
  • Confusing negative index position
  • Using range instead of start,length
  • Off-by-one errors in slicing length
4. Identify the error in this Ruby code snippet:
str = "example"
puts str[2..5, 2]
medium
A. Returns nil because of invalid range
B. Returns 'am' as expected
C. SyntaxError due to wrong slicing syntax
D. Returns 'amp' substring

Solution

  1. Step 1: Analyze slicing syntax used

    The code uses str[2..5, 2] which mixes range and length parameters incorrectly. Ruby does not support this syntax.
  2. Step 2: Understand correct slicing methods

    Use either str[2..5] for range or str[2, 2] for start and length. Mixing both causes a syntax error.
  3. Final Answer:

    SyntaxError due to wrong slicing syntax -> Option C
  4. Quick Check:

    Invalid slice syntax = SyntaxError [OK]
Hint: Use either range or start,length, not both together [OK]
Common Mistakes:
  • Mixing range and length in one slice
  • Expecting multiple parameters in range slice
  • Ignoring Ruby's slice method rules
5. Given str = "abracadabra", which code extracts every second character starting from index 0 to index 8 (inclusive)?
hard
A. str[0..8][::2]
B. str[0..8].chars.select.with_index { |_, i| i.even? }.join
C. str[0, 8, 2]
D. str[0..8].chars.each_slice(2).map(&:first).join

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]
Hint: Ruby slice has no step; use chars with index filtering [OK]
Common Mistakes:
  • Trying Python-style slicing with step
  • Using invalid slice parameters
  • Not converting string to chars before filtering
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard