ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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.


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)