This tutorial will walk you through the process of tokenizing strings using Ruby. Tokenizing is the process of splitting a string into smaller parts, or tokens, based on a specified delimiter.
Step 1: Introduction to Strings in Ruby
"This is a string in Ruby."Practice Exercise
Create a string with your name and print it.
Show Solution
name = "John Doe"
puts nameStep 2: Understanding String Tokenization
Practice Exercise
Given a sentence, tokenize it into words. For instance, 'Ruby is fun' should be tokenized into ['Ruby', 'is', 'fun'].
Show Solution
sentence = 'Ruby is fun'
tokens = sentence.split(' ')
puts tokensStep 3: Using Different Delimiters
text = "This is sentence one. This is sentence two."
sentences = text.split('.')Practice Exercise
Given a string of data separated by commas, tokenize it into an array of data points. For instance, '1,2,3,4,5' should be tokenized into ['1', '2', '3', '4', '5'].
Show Solution
data = '1,2,3,4,5'
data_points = data.split(',')
puts data_pointsStep 4: Removing Extra Whitespace
text = "This is sentence one. This is sentence two."
sentences = text.split('.').map(&:strip)Practice Exercise
Given a string of data separated by commas, tokenize it into an array of data points and remove any leading or trailing whitespace. For example, ' 1, 2, 3, 4, 5 ' should be tokenized into ['1', '2', '3', '4', '5'].
Show Solution
data = ' 1, 2, 3, 4, 5 '
data_points = data.split(',').map(&:strip)
puts data_pointsStep 5: Conclusion
Practice Exercise
Given a paragraph of text, tokenize it into sentences, then tokenize each sentence into words. Remove any extra whitespace.
Show Solution
paragraph = "This is sentence one. This is sentence two."
sentences = paragraph.split('.').map(&:strip)
words = sentences.map { |sentence| sentence.split(' ') }
puts wordsSign in to take Cornell notes on this lesson — they save automatically and stay with your account.