String Data Type
Part of the Fundamentals section of Coddy's Ruby journey — lesson 5 of 88.
In Ruby, strings are used to store text data. A string is a sequence of characters that can include letters, numbers, symbols, and spaces. Strings are one of the most commonly used data types in programming.
In Ruby, you create strings by enclosing text in quotation marks (either single ' or double " quotes). You then assign them to variables using the assignment operator =:
variable_name = "text"For example, to store the text "Hello" in a variable called greeting, you would write:
greeting = "Hello"The quotation marks tell Ruby that this is text, not a variable name or number. Without quotes, Ruby would look for a variable or method named Hello.
Examples of strings:
name = "Alice" # Text with lettersmessage = 'Welcome!' # Single quotes work tooaddress = "123 Main St" # Text with numbersempty = "" # Empty stringChallenge
EasyCreate a variable called city and assign it the string value "Paris". Then create another variable called country and assign it the string value "France". Finally, display both variables using the puts command.
Cheat sheet
In Ruby, strings store text data and are created by enclosing text in quotation marks (single ' or double "):
variable_name = "text"Examples:
name = "Alice" # Text with letters
message = 'Welcome!' # Single quotes work too
address = "123 Main St" # Text with numbers
empty = "" # Empty stringWithout quotes, Ruby would look for a variable or method instead of treating it as text.
Try it yourself
# TODO: Write the variables below
# Don't delete the rows below
puts city
puts countryThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False