Strings are a common data type we find and use in many programming languages.
As we are used to using Strings, we find that there are several common methods/functions for working with strings. Some we’ve already seen, but here are also some new ones.
size: the size operator lets us see how big a string is.
puts "Hello".size # prints 5
upcase: converts a string to all upper case
puts "Hello".upcase # prints HELLO
downcase: converts a string to all lower case characters
puts "Hello".downcase # prints hello
swapcase: swaps the case of the letters with in a string
puts "Hello".swapcase # prints hELLO
chars: converts a string to an array of letters
puts "Hello".chars
-begin
Prints out
H
e
l
l
o
-end
gsub: substitute a series of characters for another
puts "Hello".gsub("ello","i") # prints Hi
to_i and to_f converts a string to an integer number.
puts "1".to_i # prints 1
puts "1.1".to_i # prints 1 - notice it drops the decimal value
puts "1".to_f # prints 1.0
puts "1.1".to_f # prints 1.1
String Concatenation
Strings are concatenated in Ruby with the plus (+
) symbol.
answer = "1" + "1"
# answer is now "11"
Ruby will not try to convert data-types to concatenate like JavaScript, so the following example will yield an error:
puts "1" + 1 # error in type conversion
String Interpolation
You can build more complex strings by inserting values into your string. To do so, you will have a #{<variable name>}
inside of your string. This will be replaced by whatever the value of the variable is. Note that you can change data types, and it doesn’t matter.
age = 20
name = "David"
puts "Hello #{name}, you are #{age} years old."
Working with Strings in Ruby was originally found on Access 2 Learn