Sunday, January 29, 2012

Tutorial: The Beauty of Ruby with strings


Hello! We will discuss some of the features of strings but will not go in depth until future intermediate tutorials. This tutorial is intended as a teaser of the beauty ruby presents with something as simple as strings.

Lets create two strings
Code:
strOne = "Hello to all"
strTwo = 'Welcome to ruby'
The first thing we notice is that strings can be written with double quotes or single quotes.
Regardless of the quotes, the strings are still strings.

Lets look for a count of a certain character in a string.
Code:
# lets assume we want to find the number of  l's in strOne
strOne.count 'l'
# likewise we want to find out the number of w's in strTwo
strTwo.count 'w'
After running this code strOne will result in 4 and strTwo will result in 0 because we
searched for a lower case w.

Lets add to the first string and create a new string from strTwo
Code:
# instead of <<, you are free to use +
strOne = strOne << " to " << "all using this tutorial"
#strThree will be the string "ruby"
strThree = strTwo.slice(13, 4) # strTwo[13, 4] will also produce the same result

Imagine you want to see if a string contains a word, ruby syntax makes this trivial.
Code:
strOne.include? 'all'

Lets add a string.
Code:
'5'.to_i + '6'.to_i
The above code converts the string to an int and adds them.

Here goes the syntax to reverse the order of a string. This would be perfect for detecting palindromes.

Code:
'KAYAK' == 'KAYAK'.reverse
'Hello to all' == 'Hello to all'.reverse
(In a future tutorial I will go into user input and how to implement this in a application)

I hope you enjoyed this brief string intro by some common examples.

No comments:

Post a Comment