Intro to Ruby - Strings

Ruby

Introduction

You now know how to get started so lets take off the gloves and get our hands dirty.

Instructions

  • The number character(#) that proceeds any line of text in the code below is valid syntax for Ruby comments.
  • You will see the puts method used a lot below. It simply outputs each string to the console followed by a new line separator.
  • Each numbered example can be executed by copying and pasting the code in your IRB console window.
  • You can also run all numbered examples by downloading the code, unzipping the 01-strings.rb file and typing the following in a new command terminal (do not use IRB for this): ruby 01-strings.rb.
  • Again, the following is basic string manipulation in Ruby. There are plenty of methods on the Ruby string class that puts some languages to shame (yeah, I’m pointing a finger at you Java) that Ruby provides out of the box. If you don’t believe me, study the API of the String instance methods and that alone should put a smile on your face.

Code

# Double quotes.
puts "01 Hello, World"

# Single quotes.
puts '02 Hello, World'

# Double quotes but with a quoted string.
puts "03 'Hello, World!'"

# Double quote delimiter. All delimiters begin with a percent(%) sign.
puts %Q(04 Hello, World)

# Single quote delimiter.
puts %q(05 Hello, World)

# Double quotes with new lines
puts "06 Hello,\nWorld!"

# Computations using the #{expression} escape sequence.
puts "07 Multiplication: #{100 * 5}"

# Dates and Times. Another example of the #{expression} escape sequence.
# To learn more about date and time formatting via the strftime method, go here: http://apidock.com/ruby/Time/strftime
puts "08 Hello, World: #{Time.now.strftime('%B %d, %Y at %I:%M %p')}"

# String Concatenation (using the + method. Yeah, you read that right, a method NOT an operator.
# This is because everything in Ruby is an object!)
puts "09" + " Hello," + " World!"

# String Concatenation (using the << method - in this case we are appending each string to the previous string.)
puts "10 " << "Hello," + " World!"

# String Concatenation (using the an array. We'll discuss arrays soon enough so hang tight.)
puts ["11", "Hello,", "World!"].join(" ")

Output

The following is the output of the code listed above:

01 Hello, World
02 Hello, World
03 'Hello, World!'
04 Hello, World
05 Hello, World
06 Hello,
World!
07 Multiplication: 500
08 Hello, World: February 18, 2009 at 06:00 AM
09 Hello, World!
10 Hello, World!
11 Hello, World!

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 01-strings.rb.

What’s Next

Numbers.

Tags:

Wednesday, February 18th, 2009 Software

No comments yet.

Leave a comment

You must be logged in to post a comment.