Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Topics

Recent Status Updates

View All Updates

- - - - -

Tutorial: The Beauty of Ruby with strings

ruby string

  • Please log in to reply
2 replies to this topic

#1 mr mike

mr mike

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 89 posts

Posted 01 February 2011 - 07:46 PM

Hello again, its been a few weeks since my last ruby introductory tutorial. 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
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.
# 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
# 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.
strOne.include? 'all'

Lets add a string.
'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.
'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.
  • 0

#2 John


    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 04 February 2011 - 12:25 AM

Nice tutorial. So I guess
'5' + '6'
would result in 56?
  • 0

#3 mr mike

mr mike

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 89 posts

Posted 04 February 2011 - 10:35 AM

You are correct, however using '5' + '6' is only temporary. Let's assume you assigned '5' to a string.
str = '5'
str + '6' # produces the string "56" or using interactive ruby 
# now type str and the result is 5

# using irb you can test this the result will look like:
# => "5"

#If you wand to assign the 6 to 5 use <<
'5' << '6' # this makes the string "56"
#similarly, adding it to the variable can be typed 
str <<  '6'

# now type str
#=> "56" will be the result

  • 1

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download