Ruby - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Ruby Strings

Ruby String

shape Introduction

This chapter demonstrates about the Ruby String which is an object used to hold and manipulate one or more bytes of arbitrary sequence and following are the concepts covered in this chapter.
  • Strings
  • String Built in Methods

Strings

shape Description

String is an object used to hold or manipulate one or more bytes of arbitrary sequence which displays characters just like human language and another form of string is the string literals can be enclosed in single quotes whatever the text with in the quotes are known as value of the strings which is shown below. [ruby] 'Simple Programming Lessons' [/ruby] User can place the apostrophe in a single quote literal and precede with the back slash ruby interpreter doesn't think which terminates the string which is shown below. [ruby] 'Simple\'programming O\'lessons\'tutorial?' [/ruby] User can also substitute the expressions which means embed the value can be expressed in string by # Which is shown in below code. [ruby] x, y, z = 10, 26, 64 puts "The value of x is #{ x }." puts "The sum of x and y is #{ x + y }." puts "The average was #{ (x + y + z)/3 }." [/ruby] Result By running the above code in command prompt, the output can be obtained as shown in the image below. User can also built string inside a pair of arbitrary delimiter character like !,  (, {, <, % etc and some general delimited strings are shown below. [ruby] %{Ruby is fun.} equivalent to "Ruby is fun." %Q{ Ruby is fun. } equivalent to " Ruby is fun. " %q[Ruby is fun.] equivalent to a single-quoted string %x!ls! equivalent to back tick command output `ls` [/ruby] Character Encoding  ASCII is the default character set of Ruby and characters are represented with single bytes and modern character sets, UTF-8 represents  1-4 bytes. User can also change the character set with $KCODE at the starting of the snippet.
Code Description
a ASCII is default value.
e EUC
n None
u UTF-8

String Built in Methods

shape Description

In Ruby user can call string method by using instance of string object. User can create a string method which is shown below. [ruby] new [String.new(str="")] [/ruby] When user created the string object which contain copy of str by using str user can call any instance method the code below demonstrates the calling the instance method by using str as shown below. [ruby] myStr = String.new("THIS IS TEST") foo = myStr.downcase puts "#{foo}" [/ruby] Result By running the above code in command prompt, the output can be obtained as shown in the image below.

Summary

shape Key Points

  • String object contains copy of str.
  • String object is used to hold one or more bytes.
  • Ruby default character set is ASCII.