Tuesday, December 18

Ruby on Rails simple examples & String Class

After the previous post, hope you successfully installed the ruby on to your machine and ready to speed up our tutorials.
Now let us see a simple math example, factorial function. How do we write a program that would calculate the factorial value of integer that we would pass.
Basically factorial is:
n! = 1                (when n==0)
   = n * (n-1)!       (otherwise)
  • The simple logic that we are aware is, factorial is nothing but a recursive function call.
It means we write a function and will be calling the same function within that. So this would look something like this:

If you notice here there are lot of points to carry with us,
  • You may notice the repeated occurrence of end.
  • 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.
  • ARGV is an array which contains the command line arguments, and to_i converts a character string to an integer.
  1. What happens if I pass string as argument instead of integer?
  2. At the line “12”, replace the double quote with single quote and see what happens?
Download or View on Scribd

Ruby String Class:

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.

"ruby".capitalize    #=> "Ruby"

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
Find more examples and other methods ruby supports.
Download or View on Scribd

No comments: