logo codesdope

String


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]
Output
e

We can also change an element of a string like an array.

a = "Hello"
a[1] = "r"
puts a
Output
Hrllo

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
Output
as
your word comes after abc
Ruby does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters.

Some useful functions of string are:

capitalize and capitalize!

a = "hello"
puts "#{a.capitalize}"
puts "#{a}"
Output
Hello
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}"
Output
Hello
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}"
Output
helo there
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}"
Output
HELO THERE
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}"
Output
hElO tHErE
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}"
Output
5
false
olleH

split

a = "Hey! I am a programmer"
puts "#{a.split}"
Output
["Hey!", "I", "am", "a", "programmer"]

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')}"
Output
['Buggy ', 'ug ', 'uggy ', 'ug, where are you my ', 'uggy ', 'ug!']

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

Share what you know
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.