You are on page 1of 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 = n * (n-1)! (when n==0) (otherwise)

In ruby, this can be written as:
def factorial(n) if n == 0 1 else n * factorial(n-1) end end

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 1 else n * factorial(n-1) end end print factorial(ARGV[0].to_i), "\n"

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


Prepared By: Sumanth Krishna. A

Ruby on Rails : Strings

Experiment: 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)


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.

Examples: 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! capitalize: str.capitalize => new_str This method turns the first letter of the string to upper case.
"hello".capitalize #=> "Hello"

Ruby chomp: 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 "ruby\n\r".chop #=> "string" #=> "string\n"


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. insert: 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') "abcd".insert(3, 'X') #=> "Xabcd" #=> "abcXd"

length: str.length => integer Returns the length of str.

"ruby". length #=> 4 "ruby on rails". length

#=> 13

ljust: 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) "ruby".ljust(20, '1234') #=> "hello" #=> "ruby1234123412341234"

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

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

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

reverse: str.reverse => new_str Returns a new string with the characters from str in reverse order.
"stressed".reverse #=> "desserts"


Prepared By: Sumanth Krishna. A

Ruby on Rails : Strings Methods with names ending in ``!’’ modify their receiver. capitalize!: 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! a a.capitalize! #=> "Hello" #=> "Hello" #=> nil

Following is the list of methods that ruby supports for the String Class. Experiment: % , *, +, <<, <=>, == , =~, [], []= , 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?, strip!, sub!, succ, succ!, swapcase!,

squeeze!, squeeze!,

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!, References: Ruby String Class:


Prepared By: Sumanth Krishna. A