Ruby Methods

Introduction

Every method needs an object. We use def and end to declare a method.

# A method returns the value of the last line
# Methods that act as queries are often named with a trailing ?
# Methods that are "dangerous", or modify the receiver, might be named
# with a trailing ! (Bang methods)
 
def hello
    puts 'Hello'
end
 
#use the method
hello
 
#Method with an argument - 1
def hello1(name)
    puts 'Hello ' + name
    return 'sucess'
end
 
puts(hello1('satish'))
 
#Method with an argument (without brackets) - 2
def hello2 name2
    puts 'Hello ' + name2
    return 'success'
end

Default values for methods

   1. # p009mymethods1.rb  
   2. # interpolation refers to the process of inserting the result of an  
   3. # expression into a string literal  
   4. # the interpolation operator #{...} gets calculated separately  
   5. def mtd(arg1="Dibya", arg2="Shashank", arg3="Shashank")  
   6.   "#{arg1}, #{arg2}, #{arg3}."  
   7. end  
   8. puts mtd  
   9. puts mtd("ruby")

alias

alias creates a new name that refers to an existing method, operator, global variable, or regular expression backreference ($&, $‘, $’, and $+).

# alias new_name old_name  
# When a method is aliased, the new name refers  
# to a copy of the original method's body  
 
def oldmtd  
  "old method"  
end  
alias newmtd oldmtd  
def oldmtd  
  "old improved method"  
end  
puts oldmtd  
puts newmtd

Variable number of arguments

# variable number of parameters example  
# The asterisk is actually taking all arguments you send to the method  
# and assigning them to an array named my_string as shown below  
# The do end is a Ruby block which we talk in length later  
def foo(*my_string)  
  my_string.each do |words|  
    puts words  
  end  
end  
foo('hello','world')  
foo()

Bang Methods

Methods that are consider to be dangerous. They can be named with a trailing !

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

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.

Method names ending with ?

By convention, any method whose name ends with ? returns a value that answers the question posed by the method invocation.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.