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
split do when called on a string?splitsplit method breaks a string into parts wherever a separator is found.["a", "b", "c"] into a string separated by dashes in Ruby?join method is used on arrays to create a string with a separator.array.join(separator), so ["a", "b", "c"].join("-") is correct.sentence = "apple,banana,cherry"
fruits = sentence.split(",")
result = fruits.join(" & ")
puts resultsplit(",") breaks the string into ["apple", "banana", "cherry"].join(" & ") combines the array elements into the string "apple & banana & cherry".text = "hello world" words = text.split joined = words.join puts joined()
split without arguments splits on whitespace correctly. join can be called without arguments to join with empty string.puts joined()joined() causes an error because joined is a string, not a method.joined() is incorrect syntax. -> Option Cdata = "red;green;blue;yellow", write Ruby code to split it into an array, remove the color "blue", and then join the remaining colors with commas. What is the correct output?split(";") on data gives ["red", "green", "blue", "yellow"].array.delete("blue") or array.reject!.join(",") results in "red,green,yellow".Pass the test and this pattern moves unknown