You have already been introduced with strings.
a = "Hey there"
Like array, string is also a collection. String is a collection of characters and they are written within (' ') or (" ").
a = "Hello"
puts a[1]
We can also change an element of a string like an array.
a = "Hello"
a[1] = "r"
puts a
String comparison
Comparison of string in Ruby is very simple. We just use '==', '<,' ,'>' ,'>=' , '<=' operators. Let's see an example:
a = gets.chomp
if a>"abc"
puts 'your word comes after abc'
elsif a<"abc"
puts 'your word comes before abc'
else
puts 'your word is abc'
end
your word comes after abc
Some useful functions of string are:
capitalize and capitalize!
a = "hello"
puts "#{a.capitalize}"
puts "#{a}"
hello
capitalize capitalizes a string. Notice that the change was only when it was called and not in 'a'. To make changes in the initial string, we can use capitalize!
a = "hello"
puts "#{a.capitalize!}"
puts "#{a}"
Hello
You can see that by using capitalize!, changes have also been made in the original string.
downcase and downcase!
Changes every character of a string to lower case.
a = "HeLo TheRe"
puts "#{a.downcase}"
puts "#{a}"
puts "#{a.downcase!}"
puts "#{a}"
HeLo TheRe
helo there
helo there
upcase and upcase!
Changes every character of a string to upper case.
a = "HeLo TheRe"
puts "#{a.upcase}"
puts "#{a}"
puts "#{a.upcase!}"
puts "#{a}"
HeLo TheRe
HELO THERE
HELO THERE
swapcase and swapcase!
Inverses case of every character of a string.
a = "HeLo TheRe"
puts "#{a.swapcase}"
puts "#{a}"
puts "#{a.swapcase!}"
puts "#{a}"
HeLo TheRe
hElO tHErE
hElO tHErE
length, empty? and reverse are same as we used with arrays.
a = "Hello"
puts "#{a.length}"
puts "#{a.empty?}"
puts "#{a.reverse}"
false
olleH
split
a = "Hey! I am a programmer"
puts "#{a.split}"
The split function splits a string when it encounters space(" ") and put them into an array.
To split at a particular place.
We can also use the split function to split a string with something other than a 'space'. Let's see how:
a = "Buggy bug buggy bug, where are you my buggy bug!"
puts "#{a.split('b')}"
Here we wanted our string to split at 'b'. So, we passed 'b' to the 'split()' function and it's done.
You can find more methods at Ruby documentation
Winning doesn't come cheaply. You have to pay big a price.
-Jeev Milkha Singh