Ruby Methods

Method are implement a pattern. That can be contains group of instruction and statements which are used to solve particular task. This is also know as function in other Programming Language. The main advantage of function are it will be define once. And that is can used in a so many times of during program execution. That is very effective mechanism that are provide reusability of code.

Define Method

def are used to define a method in Ruby Programming after that mentions the name of method, within the parenthesis providing the parameters of function that is are optional if function are not accepting any value.

def methodeName(paramterList)
  #Method statements
end

Argument are also known as parameter of list method. When method are accepted more than one parameter values then in this situation each parameter is separate by (,) comma. And last end keyword are used to closing the body of method. let's see few examples to declaration of methods.

def message()
  #method statement here
end 

def salary(employeeId)
  #method statement here
end

#num1 and num2 are formal parameters of sum method
def sum(num1,num2)
  #method statement here
end

In this example program are not produce any output. But remember that everything in ruby programming is form of an objects. So name of method is an identifier which are hold the reference of methods.

Method Instance In Ruby Programming

Name of method are used to execute inside method instruction

Ruby Method Categories

Behaviour of function are provided the information about how it will work and used. parameter list, name of function and returning value of method is important part of method. So we can categories of methods in following section based on its behaviour.

Function Without Arguments

That is normal case when you'll are needed to define a method which are not accept any values but they are perform some operation and display resultant message.

Function With Arguments

function argument are provide dynamic environment when inside of method instruction are used this parameter value to perform some operation.

Function Without Returning

Some of case, we are define a function that are perform some operation and not returns any values. For example in class constructor is used to set initial value of class properties. This function can accept parameter argument. But individually not return any value.

Function With Returning

return statement are used to returning value by function. In ruby programming there is possible to return single and multiple values by function. That is depending upon situations.

def testOne(num1,num2)
  #returns result of sum of two number
  return num1+num2
end

def testTwo
  #return return array of two element
  return 1,2
end 

one, two = testTwo
puts one  # 1
puts two  # 2

puts testOne one,two # 3
Returning reference of array by method

In this example testTwo are return an array but variable (one, two) are gets there single element value. That is very basic example that are returning an array which is contain two values. But when array contain undefine elements so we can use single variable which storing the reference of array. Let see this example

#method are returning an array
def fibonacci(size)
  arr_element=[]
  current,last = 1,0
  while size>0 do
    #add element to array 
    arr_element.push current
    current,last = current+last ,current
    size-=1
  end
  return arr_element
end

setOne = fibonacci(5)
setTwo = fibonacci(10)
print setOne
print "\n"
print setTwo
[1, 1, 2, 3, 5]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Returning reference of array by method

Function With Default Parameter

Default argument are used to when given argument is optional. In this situation we can set default value to function argument. This default value are automatic assign when not provide any value to that paramter.

#Set default value of parameter
def test data1,data2=[10,20,30,40]
  print "\n data1 : "
  print data1
  print "\n data2 : "
  print data2
end
test 5 , 10
test 200    #used default variant
method default parameter
 data1 : 5
 data2 : 10
 data1 : 200
 data2 : [10, 20, 30, 40]

Arbitrary numbers of arguments

There is an special case, when function are capable to get any number of parameter which is provided by the calling function. (*) asterisk allows arbitrary numbers of arguments. That is appended by formal parameter of argument variable. That is indicates which are accepted any number of passing argument. This passing argument internally created an array instance and retrieve passing parameter values.

#Method which are accepting arbitrary numbers of arguments
def test(*args)
  puts "\nNumber of parameter : #{args.size}"
  args.each do |element|
    puts element
   
  end
end
#pass four argument to method
test 1,2,3,4
#passing three argument to method
test "one","two","three"

#passing two argument to method
test "one",134

#passing  empty argument
test

In this example there are 4 different argument are passed in test() method. test function are capable to accepting this parameter values. That means one variant of method are work all different variant of parameter list.

Arbitrary numbers of argument in ruby
Number of parameter : 4
1
2
3
4

Number of parameter : 3
one
two
three

Number of parameter : 2
one
134

Number of parameter : 0

Nested Function

Defining of a function inside a another function, it is called nested functions. That is commonly used when solve complex problem. There is declare using following syntax.

def outer
  #define inner method
  #inner is method name
  def inner
    #method statement
  end

  #define inner method
  def test
    #method statement
  end
end

Overriding Method

Overriding is a way to redefine an existing method.

def test
  puts "Hello, programmer"
end

def test
  puts "Hello, Developer"
end

test #Hello, Developer

Adding a method to an object

#make string objects
coder  = "Run"
tester = "Test"
#add method in an object's
def coder.info(message)
 puts(self +" "+ message + " Codes")
end

def tester.info(message)
 puts(self +" or debug "+ message + " Codes")
end

coder.info  "Ruby"   # Run Ruby Codes

tester.info "Ruby"  # Test or debug Ruby Codes

Default Parameter Values

def info(first=10,second=20) #set default values
  puts " first : #{first}  second : #{second}"
end
info() #when both are initialize default value
info(12) #second paramter is default initialize
info(30,2) #no default value
 first : 10  second : 20
 first : 12  second : 20
 first : 30  second : 2

Method Aliasing

class Auxiliary
  #define a method
  def test_info
    puts "Test Info"
  end
  #alias method name
  alias :new_test :test_info

end

obj=Auxiliary.new
obj.new_test #Test Info

Keyword Arguments

def info(data:) #data label 
  puts data
end
#Passing method argument by label arguments
info(data:"Hello") 
Hello
def info(first:,second:) #data label 
  puts " first : #{first}  second : #{second}"
end
#Passing method argument by label arguments
info(second:"200",first:"100")

#when exchange of label position
info(first:"one",second:"two")
 first : 100  second : 200
 first : one  second : two


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved