learn ruby string

wang xiao bo 's photo
wang xiao bo

Published on Sep 1, 2021

2 min read

Subscribe to my newsletter and never miss my upcoming articles

puts "I love ICE CREAM".downcase

//strip method to remove extra spaces from the start and from the end of a string
puts "   Bobo   ".strip

//the to_s method to convert an integer to string. to_s stands forto string”. Let’s use to_s on 24 to make it a string.
puts "Ruby is " + 24.to_s + " years old now"

//use the to_i method. to_i is a short form for to integer.
puts "18".to_i + 2

//the capitalize method to turn only the first letter of a string into a capital letter.
puts "miami".capitalize

//In Ruby, we can call multiple methods one after another.
name = "John Smith"
puts name.upcase.downcase.capitalize

//First position is zero not 1
string = "hello"
puts string[0]

//use -1 to find the last letter of the string hello.
string = "hello"
puts string[-1] //o

// next to last? For that, we can use -2.
string = "hello"
puts string[-2] //l

//start_with? to check if a string starts with the given string.
name = "Bobo xiao"
puts name.start_with("Bobo") // true
puts name.start_with("Bo") // true

//include? to check if a string includes another string.
name = "Bobo xiao"
puts name.include?("xiao") // true
puts name.include?("xi") // true

//chars to convert a string into a list of characters.
name = "Bobo"

characters = name.chars

puts "printing all characters"
puts characters // ["B", "o", "b", "o",]

puts "printing 3rd character"
puts characters[2] // b

//using double quoted string
name = "Bobo xiao"
greetings = "Good morning #{name}"
puts greetings

Given below is the list of escape sequences with their corresponding meaning:

`     Single quote
"     Double quote
\a     Audible bell
\b     Backspace
\f     Form feed
\r     Carriage return
\s     A space
\t     Horizontal tab
\n     New line

string = "I am John.\n I am 25 years old"
puts  string

//Get a Part of the String
game = "basketball"
puts game[0,6] // basket
 
Share this