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.
If you notice here there are lot of points to carry with us,
- You may notice the repeated occurrence of
- You may also notice the lack of a
- It is not needed because a ruby function returns the last thing that was evaluated in it. Though use of a
returnstatement is permissible but it is not necessary here.
ARGVis an array which contains the command line arguments, and
to_iconverts a character string to an integer.
- 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?
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! #=> nilFind more examples and other methods ruby supports.
Download or View on Scribd