Вы находитесь на странице: 1из 5

Ruby on Rails : Strings

Today we will look into few examples and introduce on strings with working examples.

Say we start on simple math factorial function

The mathematical definition of n factorial is:

n! = 1 (when n==0)
= n * (n-1)! (otherwise)

In ruby, this can be written as:

def factorial(n)
if n == 0
n * factorial(n-1)

You may notice the repeated occurrence of end.

(Note: the syntax of ruby more closely mimics that of a language named Eiffel.)

You may also notice the lack of a return statement. It is not needed because a ruby
function returns the last thing that was evaluated in it. Though use of a return statement
is permissible but it is not necessary here.

Let's try out our factorial function. Adding one line of code gives us a working program:

# Program to calculate the factorial of a number

# Save this as factorial.rb

def factorial(n)
if n == 0
n * factorial(n-1)

print factorial(ARGV[0].to_i), "\n"

ARGV is an array which contains the command line arguments, and to_i converts a
character string to an integer.

1 Prepared By: Sumanth Krishna. A

Ruby on Rails : Strings

What happens if I pass string as argument instead of integer?
At the line “12”, replace the double quote with single quote and see what happens?(It
will be discussed in next page)

2 Prepared By: Sumanth Krishna. A

Ruby on Rails : Strings

A String object holds and manipulates an arbitrary sequence of bytes, typically

representing characters. String objects may be created using String::new or as literals.

Because of aliasing issues, users of strings should be aware of the methods that modify
the contents of a String object.

• Methods with names ending in ``!’’ modify their receiver.

• Methods without a ``!’’ return a new String.

Ruby deals with strings as well as numerical data. A string may be double-quoted ("...")
or single-quoted ('...').

• A double-quoted string allows character escapes by a leading backslash, and the

evaluation of embedded expressions using #{}.
• A single-quoted string does not do this interpreting; what you see is what you get.


If you had done the above mentioned experiments, it is easy to understand the above two
points. The difference between the double and single quotes around a string. There are
plenty of methods that ruby offers, they come very handy!


str.capitalize => new_str

This method turns the first letter of the string to upper case.

"hello".capitalize #=> "Hello"



str.chomp(separator=$/) => new_str

Returns a new String with the given record separator removed from the end of str (if
present). If $/ has not been changed from the default Ruby record separator, then chomp
also removes carriage return characters (that is it will remove \n, \r, and \r\n).
"ruby\r\n".chop #=> "string"
"ruby\n\r".chop #=> "string\n"

3 Prepared By: Sumanth Krishna. A

Ruby on Rails : Strings

In Ruby, strings are mutable. They can expand as needed, without using much time and
memory. Ruby stores a string as a sequence of bytes.

str.insert(index, other_str) => str
Inserts other_str before the character at the given index, modifying str. Negative indices
count from the end of the string, and insert after the given character. The intent is insert
aString so that it starts at the given index.
"abcd".insert(0, 'X') #=> "Xabcd"
"abcd".insert(3, 'X') #=> "abcXd"

str.length => integer
Returns the length of str.
"ruby". length #=> 4
"ruby on rails". length #=> 13

str.ljust(integer, padstr=' ') => new_str
If integer is greater than the length of str, returns a new String of length integer with str
left justified and padded with padstr; otherwise, returns str.
"hello".ljust(4) #=> "hello"
"ruby".ljust(20, '1234') #=> "ruby1234123412341234"

str.lstrip => new_str
Returns a copy of str with leading whitespace removed.
" hello ".lstrip #=> "hello "
"hello".lstrip #=> "hello"

str.rstrip => new_str

Returns a copy of str with tailing whitespace removed.
" hello ".lstrip #=> " hello"

str.replace(other_str) => str
Replaces the contents of str with the corresponding values in other_str.
s = "java" #=> "java"
s.replace "Ruby" #=> "Ruby"


str.reverse => new_str

Returns a new string with the characters from str in reverse order.

"stressed".reverse #=> "desserts"

4 Prepared By: Sumanth Krishna. A

Ruby on Rails : Strings

Methods with names ending in ``!’’ modify their receiver.

str.capitalize! => str or nil
Modifies str by converting the first character to uppercase and the remainder to
lowercase. Returns nil if no changes are made.
a = "hello"
a.capitalize! #=> "Hello"
a #=> "Hello"
a.capitalize! #=> nil

Following is the list of methods that ruby supports for the String Class.


% , *, +, <<, <=>, == , =~, [], []= ,

block_scanf, capitalize , casecmp, center, chomp, chop, concat, count, crypt,

delete, downcase, dump, each, each_byte, each_char, each_line, hash , hex,
index, initialize_copy, end_regexp, gsub, insert, inspect, intern, issjis, isutf8,
jcount, jlength, jsize, kconv, length, ljust, lstrip , iseuc, replace, reverse, Oct,
quote , match , New, next, rindex, rjust, rstrip, scan, scanf, size, slice, split,
squeeze, squeeze, strip, sub, sum, swapcase, unpack, upcase, upto, yaml_new

chomp!, capitalize!, chop!,delete!, downcase!, gsub!, lstrip!, next!, reverse!, rstrip!,

slice!, upcase!,

empty?, eql?, include?, is_binary_data?, is_complex_yaml?, mbchar?,

squeeze!, squeeze!, strip!, sub!, succ, succ!, swapcase!,

to_f, to_i, to_s, to_str, to_sym, to_yaml toeuc tojis tosjis toutf16 toutf8 tr
tr, tr!, tr!, tr_s, tr_s!,

Ruby String Class: http://ruby-doc.org/core/classes/String.html

5 Prepared By: Sumanth Krishna. A