: 
http://rubylearning.com/
http://rubylearning.com/satishtalim/tutorial.html
http://rubylearning.com/download/downloads.html
http://rubylearning.com/other/certification.html
http://rubylearning.com/blog/
http://rubylearning.com/other/ruby_news.html
http://rubylearning.com/other/testimonials.html
http://rubylearning.com/jobs/ruby_jobs.html
http://rubylearning.com/other/ruby_gurus.html
http://rubylearning.com/satishtalim/services.html
http://rubylearning.com/contact/contact.html
http://rubylearning.com/satishtalim/about.html


Writing own 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 line. 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.



# A simple method

def hello

  puts 'Hello'

end

#use the method
hello
# Method with an argument - 1
def hello1(name)
 puts 'Hello ' + name
 return 'success'
end

puts(hello1('satish'))

# Method with an argument - 2
def hello2 name2
 puts 'Hello ' + name2
 return 'success'
end

puts(hello2 'talim') # A method returns the value of the last line


The output is:


>ruby mymethods.rb

Hello

Hello satish

success

Hello talim

success

mymethods.rb:20: warning: parenthesize argument(s) for future version

>Exit code: 0

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


def mtd(arg1="Dibya", arg2="Shashank", arg3="Shashank")

  "#{arg1}, #{arg2}, #{arg3}."

end

puts mtd

puts mtd("ruby")


The output is:


>ruby mymethods1.rb

Dibya, Shashank, Shashank.

ruby, Shashank, Shashank.

>Exit code: 0

In the above program the interpolation operator #{...} gets calculated separately (please refer to expression interpolation for more details on this), 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.


The example p010aliasmtd.rb talks about Aliasing a method.

alias new_name old_name

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.


def oldmtd

  "old method"

end

alias newmtd oldmtd

def oldmtd

  "old improved method"

end

puts oldmtd

puts newmtd


The output is:


>ruby aliasmtd.rb

>Exit code: 0

>ruby aliasmtd.rb

old improved method

old method

>Exit code: 0

Does Ruby allow us to write functions that can accept variable number of parameters? Yes, see the following example - p011vararg.rb


def foo(*my_string)

  my_string.each do |words|

    puts words

  end

end

foo('hello','world')

foo()

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 which we talk in length here. 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:


>ruby vararg.rb

hello

world

>Exit code: 0


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. You can refer to: http://www.recentrambles.com/pragmatic/view/68


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


def mtd(a=99, b=a+1)

  [a,b]

end

puts mtd


Are the parameters passed by value or reference?  Have a look at this url -

http://dev.rubycentral.com/faq/rubyfaq-4.html

and see this example:


def downer(string)

  string.downcase!

end

a = "HELLO"    # -> "HELLO"

downer(a)      # -> "hello"

a


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.




Learning Ruby Navigation                                                          <More on Methods  | TOC  |  Method Missing>