Split and Join
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 4 of 56.
The split method breaks a string into an array of smaller strings. By default it splits on whitespace:
"the quick fox".split
# ["the", "quick", "fox"]Pass any delimiter to split on something else:
"a,b,c,d".split(",")
# ["a", "b", "c", "d"]The opposite operation is join, called on an array. It glues the elements together with the separator you provide:
["a", "b", "c"].join("-")
# "a-b-c"Together, split and join are how you reshape text in Ruby.
Challenge
EasyRead a comma-separated list of words. Print them joined back together with " - " (space, dash, space) between each, with every word in uppercase.
For input red,green,blue, the output is:
RED - GREEN - BLUECheat sheet
split breaks a string into an array (default: whitespace):
"a,b,c".split(",") # ["a", "b", "c"]join glues an array into a string with a separator:
["a", "b", "c"].join("-") # "a-b-c"Try it yourself
input = gets.chomp
# TODO: split on ",", uppercase each word, join with " - "
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier