0
0
Rubyprogramming~10 mins

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

Choose your learning style9 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.