Writing Own Ruby Methods
Let's look at writing one's own methods in Ruby with the help of a simple program p008mymethods.rb. Observe that we use def and end to declare a method. Parameters are simply a list of local variable names in parentheses.
We do not declare the return type; a method returns the value of the last statement. It is recommended that you leave a single blank line between each method definition. As per the Ruby convention, methods need parenthesis around their parameters. However, since puts, p (more on this later) and gets are extensively used, the rule of parenthesis is not applicable. In Rails, you will see methods calls with no parentheses.
The output when I ran the program on my PC was:
When you run the above program in 1.9, the warning: parenthesize argument(s) for future version is not displayed. Yukihiro Matsumoto (Matz) clarified that he had earlier added the warning for ease of future reimplementation of the parser, but the plan was cancelled. In addition, somebody (forgot his name, sorry) persuaded him that the unparenthesized arguments are useful to implement DSL in Ruby. Therefore from 1.9, you can have unparenthesized arguments to methods.
Ruby lets you specify default values for a method's arguments-values that will be used if the caller doesn't pass them explicitly. You do this using the assignment operator. See example p009mymethods1.rb
The output when I ran the program on my PC was:
Please note that as of now, there is no way, to specify a value for the second parameter and use the default value of the first parameter.
In the above program the interpolation operator #{...} gets calculated separately and the results of the calculation are pasted automatically into the string. When you run these lines, you don't see the #{...} operator on your screen; instead, you see the results of calculating or evaluating what was inside that operator.
Note: Interpolation refers to the process of inserting the result of an expression into a string literal. The way to interpolate within a string is to place the expression within #{ and } symbols. An example demonstrates this:
This displays:
The #{100 * 5} section interpolates the result of 100 * 5 (500) into the string at that position, resulting in the output shown.
The example p010aliasmtd.rb talks about Aliasing a method.
creates a new name that refers to an existing method. When a method is aliased, the new name refers to a copy of the original method's body. If the method is subsequently redefined, the aliased name will still invoke the original implementation.
The output is:
alias creates a new name that refers to an existing method, operator, global variable, or regular expression backreference ($&, $`, $', and $+). Local variables, instance variables, class variables, and constants may not be aliased. The parameters to alias may be names or symbols.
Does Ruby allow us to write functions that can accept variable number of parameters? Yes, see the following example - p011vararg.rb
The asterisk is actually taking all arguments you send to the method and assigning them to an array named my_string. The do end is a Ruby block. As you can see, by making use of the asterisk, we're even able to pass in zero arguments. The code above will result in the words hello and world written on successive lines in the first method call and nothing being written on the second call, as you can see in the following output:
If you want to include optional arguments (*x), they have to come after any non-optional arguments:
def opt_args(a,b,*x) # right
def opt_args(a,*x,b) # wrong
What is the maximum number of parameters we can pass in Ruby? There's no limit to the number of parameters.
What is the sequence in which the parameters are put on to the stack? Left to right like C or right to left like Pascal? The answer is Left to right as you can see in this example p012mtdstack.rb
Are the parameters passed by value or reference? Observe the following example:
Bang (!) Methods
Ruby methods that modify an object in-place and end in an exclamation mark are known as bang methods. By convention, the bang labels a method as dangerous - specifically, as the dangerous equivalent of a method with the same name but without the bang.
You'll find a number of pairs of methods, one with the bang and one without. Those without the bang perform an action and return a freshly minted object, reflecting the results of the action (capitalizing a string, sorting an array, and so on). The bang versions of the same methods perform the action, but they do so in place: Instead of creating a new object, they transform the original object.
Examples of such pairs of methods include sort/sort! for arrays, upcase/upcase! for strings, chomp/chomp! for strings, and reverse/reverse! for strings and arrays. In each case, if you call the non-bang version of the method on the object, you get a new object. If you call the bang version, you operate in-place on the same object to which you sent the message.
Ruby lets you define a method whose name ends with an exclamation point. The exclamation point, or bang, has no significance to Ruby internally; bang methods are called and executed just like any other method. However, by convention, the bang labels a method as dangerous - specifically, as the dangerous equivalent of a method with the same name but without the bang.
Dangerous can mean whatever the person writing the method wants it to mean. In the case of the built-in classes, it usually (although not always) means this method, unlike its non-bang equivalent, permanently modifies its receiver.
You'll find a number of pairs of methods, one with the bang and one without. Those without the bang perform an action and return a freshly minted object. The bang versions of the same methods perform the action, but they do so in place: Instead of creating a new object, they transform the original object.
A few non-bang methods perform changes on the original string. The names of these methods make it clear that this is happening (such as replace), even though there’s no ! on the name.
Method names ending with ?
The question mark has no special meaning to the Ruby interpreter. However, by convention, any method whose name ends with ? returns a value that answers the question posed by the method invocation. The empty? method of an array, for example, returns true if the array has no elements. Mostly such methods return one of the Boolean values true or false, but this is not required, as any value other than false or nil works like true when a Boolean value is required. The Numeric method nonzero?, for example, returns nil if the number it is invoked on is zero, and just returns the number otherwise.
Summary
I have listed down all the important points you need to remember after you have completed the following topics: Scope, Getting Input, Ruby Names, More on Ruby Methods, Writing on Ruby Methods.