String Operations
Lesson 6 of 48 in Coddy's Ruby for C++ Developers course.
C++ std::string owns a sequence of char units, commonly UTF-8 bytes, and size counts those units. Ruby strings carry an encoding, and length counts characters in valid encoded text. Ruby upcase returns a transformed string; upcase! mutates its receiver. Do not confuse a copied C++ string value with an aliased Ruby string object.
C++: complete program
#include <iostream>
#include <string>
int main() {
std::string text="cat"; std::cout << text.size() << ":" << text.substr(1,2) << "\n";
}
Ruby: complete program
name = "elm"
puts "<#{name.upcase}>"
puts nameChallenge
EasyStrip surrounding whitespace, lowercase the input and replace each internal space with a hyphen. Internal repeated spaces each produce a hyphen. Input contains ASCII letters and spaces. Return (empty) if the result is empty.
Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.
Your code goes in exercise.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
def check(value)
raise 'Public API check failed' unless value
end
puts solve(STDIN.read)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for C++ Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: BorrowPractice on your own: Online Ruby compiler