ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Strings In Ruby

Updated on February 19, 2013

Ruby is an extremely clean and easy language to learn. Like any language it has its own way to manage strings. Strings in Ruby program are instances of the String class. There are different ways you can create a string in Ruby and processing it using the String API.

Creating Strings

In Ruby you can use single and double quote delimiters.

When using single quote delimiters there is almost no interpretation of the text apart from escaping the backslash '\':

text = 'I don\'t like bad food and I like backslashes like this: \\'
puts text

that will print out:

I don't like bad food and I like backslashes like this: \

Double quote strings can parse special characters like tab '\t', newline '\n', etc. and arbitrary expressions between #{}. Example:

name = "John"
surname = "Smith"
my_details = "Details\n\tName: #{name}\n\tSurname: #{surname}"
puts my_details

It will print:

	Name: John
	Surname: Smith

In a double quotes string you need to escape double quotes with \" but not single quotes '. In a single quotes string is the opposite.

Anyway if you really hate escaping quotes you can always use this way to write a string:

text = %q{This is a quoted "text" and I don't like backslashes}

You can replace '{}' with '<>', '[]' or other special characters like "$$".

'q' is the equivalent of the single quotes and 'Q' is the equivalent of the double quotes. So you can have something like this:

name = "John"
text = %Q{my name is "#{name}". Nice, isn't it?}
puts text

and you will get:

my name is "John". Nice, isn't it?

You can even write multiline strings:

text = "example of multiline 

text = %q{example of multiline 

text = %Q{example of multiline 

They will all give you:

example of multiline

You can avoid multiline in %Q using '\' like this:

text = %Q{example of multiline \

that will result in:

example of multiline string

For very long multi line texts you can consider using this form:

text = <<EOF
this is a very long text and
blah blah and
blah blah and
blah blah and

It is possible to "multiply" a string:

puts "Ruby is " + "very " * 3 + "cool!"

that generates:

Ruby is very very very cool!

You can refer to a single character in a string using square brackets and an index like an array. If you use a negative index the reference of the string will start from right to left. Example:

text = "This is a test"
puts text[1]
puts text[-6]

It will show:


Powerful String API

The Ruby String API is really powerful and complete. Here is a list of some most important commands and examples:

lstrip returns a copy of string with leading whitespace removed:

' hello'.lstrip => 'hello'

rstrip returns a copy of string with trailing whitespace removed:

'hello '.rstrip => 'hello'

strip returns a copy of string with leading and trailing whitespace removed:

' hello '.strip => 'hello'

chomp returns a copy of string with given separator removed (if any separator is not specified it will remove \n, \r and \r\n):

'hello'.chomp('lo') => 'hel'

chop returns a copy of string with the last character removed:

'hello'.chop => 'hell'

upcase returns a copy of string with all letters replaced by their uppercase counterpart:

'hEllO'.uppercase => 'HELLO'

downcase same as upcase but with lowercase letters:

'hEllO'.downcase => 'hello'

swapcase returns a copy of string with lowercase and uppercase letters inverted:

'hEllO'.swapcase => 'HeLLo'

sub returns a copy of string with the first occurrence of reg-exp replaced with the second parameter:

'hello'.sub /[aeiou]/, '-' => 'h-llo'

gsub returns a copy of string with all occurrences of reg-exp replaced with the second parameter:

'hello'.gsub /[aeiou]/, '-' => 'h-ll-'

split returns an array of substrings from splitting the string by a delimiter:

'this is a test'.split(' ') => ["this", "is", "a", "test"]

replace replaces the content of a string with another string:

'hello'.replace 'ruby' => "ruby"

insert inserts a string before the character at the given index (including negative indexes):

'hello'.insert(0, 'w') => 'whello'

size returns the length of string:

'hello'.size => 5

NOTE: some of the commands discussed above have a counterpart followed by '!'. for example strip!, chop!, etc. The main difference is that they don't return a copy of the string but they modify the string object self.

For more commands, descriptions and examples see here.

String Comparison

Strings comparison is performed either using the == or eql? methods:

"Hello" == "World" => false

"Hello".eql? "Hello" => true

It is possible to compare two strings with '<=>' in relation to their "ASCII position". It will return 0 if the strings are identical, -1 if the left string is less than the right string, and 1 if it is greater:

"Hello" <=> "Hello" => 0

"Hello" <=> "World" => -1

"World" <=> "Hello" => 1

To perform a case insensitive comparison you can use 'casecmp' method that will return 0, -1, 1 same as in '<=>' above.

"Ruby".casecmp "ruby" => 0

What do you think about Ruby?

We want to know your opinion!

See results


    0 of 8192 characters used
    Post Comment

    No comments yet.