Ruby Fundamentals: Manipulating Variables
Master Ruby string manipulation with hands-on examples
This tutorial uses IRB (Interactive Ruby) to provide immediate feedback as you practice string manipulation concepts. Keep your Terminal open throughout the lesson for the best learning experience.
Ruby String Fundamentals
String Creation
Learn how to create and assign string values to variables in Ruby. Understand the basic syntax and structure.
String Methods
Explore built-in methods like capitalize, upcase, and length. Master method chaining for complex operations.
String Manipulation
Work with substrings, ranges, and regular expressions for advanced string processing and pattern matching.
Creating Your First String
Open IRB
Launch Terminal and type 'irb' to start the Interactive Ruby interpreter
Create Variable
Type 'name = "fluffy"' to create a string variable with the value fluffy
Call Variable
Type 'name' to display the stored string value and verify creation
Temporary vs Permanent String Changes
| Feature | Without Exclamation | With Exclamation |
|---|---|---|
| Method Example | name.capitalize | name.capitalize! |
| Result Persistence | Temporary | Permanent |
| Original Variable | Unchanged | Modified |
Ruby processes chained methods from left to right. name.capitalize.reverse gives 'yffulF' while name.reverse.capitalize gives 'Yffulf' - the order of operations creates different results.
String Indexing in Ruby
Remember that Ruby uses zero-based indexing. The first character is at position 0, not 1. This is consistent with most programming languages and essential for working with arrays.
Two Periods vs Three Periods in Ranges
| Feature | Two Periods (..) | Three Periods (...) |
|---|---|---|
| Syntax Example | name[0..2] | name[0...2] |
| End Position | Included | Excluded |
| Result for 'Fluffy' | 'Flu' (3 chars) | 'Fl' (2 chars) |
String Comparison Methods
Equality Check (==)
Compare two strings for exact match. Returns true if strings are identical, false otherwise.
Include Method
Check if a substring exists within a larger string. Useful for finding specific words or patterns.
Start/End Methods
Verify if strings begin or end with specific text. Adds precision to string validation.
Regular expressions are like an advanced find/replace. They are written between two forward slashes and are used to perform partial matches.
Using gsub with Regular Expressions
Create Source String
Define the original string that contains text you want to replace
Write Regex Pattern
Enclose the search pattern between forward slashes like /Fluffy/
Apply gsub Method
Use string.gsub(/pattern/, 'replacement') to replace all matches
Key Takeaways