Concept Flow - Split and join methods
Start with a String
Use split method
Get Array of substrings
Use join method on Array
Get new String combined
Split breaks a string into parts (array), join combines array parts into a string.
text = "apple,banana,cherry" words = text.split(",") result = words.join("-") puts result
| Step | Action | Input | Output | Notes |
|---|---|---|---|---|
| 1 | Start with string | "apple,banana,cherry" | "apple,banana,cherry" | Original string assigned to text |
| 2 | Split string by ',' | text.split(",") | ["apple", "banana", "cherry"] | Split creates array of words |
| 3 | Join array with '-' | words.join("-") | "apple-banana-cherry" | Join combines array into string with dashes |
| 4 | Print result | puts result | apple-banana-cherry | Output to console |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| text | "apple,banana,cherry" | "apple,banana,cherry" | "apple,banana,cherry" | "apple,banana,cherry" |
| words | nil | ["apple", "banana", "cherry"] | ["apple", "banana", "cherry"] | ["apple", "banana", "cherry"] |
| result | nil | nil | "apple-banana-cherry" | "apple-banana-cherry" |
Split and join methods in Ruby: - split(separator) breaks a string into an array by separator - join(separator) combines array elements into a string with separator - split returns an array, join works on arrays - Commonly used together to transform string formats