codedecoder

breaking into the unknown…

methods in ruby

2 Comments

A method can be define as below:

A method is a named block of parameterized code associated with one or more objects.

ruby supports different type of methods, exhibiting different behaviour in terms of its invocation and visibility. before we look into different types of methods. let us write some methods and see how they behave. create a file method_demo.rb . We will execute these method in irb and keep defining the method type along with it.

NOTE : before you proceed, I assume that you know about self , receiver , ancestor chain and method lookup. If not, it doesn’t make much difference, but knowing them help to understand the concept in better way, so read out it here .

# global method
def iam_global_method
  puts "Iam defined outside class or module at top of the file"
end

# class to demo different methods in ruby
class MethodDemo

  def iam_instance_method
    puts "I can be exicuted only on object of my class"
  end

  def self.iam_class_method
    puts "I can be exicuted on my class, not on its object"
  end

  def demo_explicit_return
    @name = "Arun"
    return "santosh", "kapil"
    puts "I want to get exicuted"
    @name
  end

  def demo_implicit_return
    @name = "Arun"
    puts "I want to get exicuted"
    @name
  end

  def i_will_be_aliased
    puts "you can create aliase of any method"
  end

  def aliase_method
    puts "Iam synonym of my aliase. old method can be called by my name"
  end

  alias :aliase_method :i_will_be_aliased

end

# class inheriting the above class
class SubMethod < MethodDemo
  def global_method_in_subclass
    iam_global_method
  end
end

#any class, not inheriting above classes
class AnyMethod
  def global_method_anyclass
    iam_global_method
  end
end

#it will demonstrate use of alias method
class String
  alias :old_to_i :to_i
  def to_i
    raise "No digits found" unless match(/\d/)
    old_to_i
  end
end

#object or instance singleton method
@method_demo_singleton = MethodDemo.new

#defining singleton method on object
def @method_demo_singleton.only
  puts "only method is availabe only to object @method_demo_singleton"
end

We will call these method on irb and see how they behaves .

$irb # will open the irb console
> load “/home/arun/Desktop/self.demo.rb” # will load the code of method_demo.rb file . read more about load and require in ruby
true # it means your file is loaded successful on the irb console

1 => Global method :

  1. Global methods are defined at top context of a file i,e outside the class or module at the top
  2. Global methods belongs to main:object
  3. Global methods are private method of the main object and so can be accessed privately in all the classes inheriting from it.The ruby object hierarchy is  :  basic_object -> object (global method belongs to it) -> object of custom class A -> class B … so on. So you can conclude that global method is accessible in all the object in your application, but privately i,e without a explicit receiver
  4. Global method visibility is private but accessible through out the application

 

The above points can be illustrated with below output :

> iam_global_method #calling global method with implicit receiver
Iam defined outside class or module at top of the file
> self.iam_global_method # calling with self as receiver
NoMethodError: private method `iam_global_method’ called for main:Object # error thrown
>@subm = SubMethod.new #creating object of Sub class
=> #<SubMethod:0xa00c030>
>@subm.global_method_in_subclass #calling the global method on the subclass object
Iam defined outside class or module at top of the file
> @anym = AnyMethod.new # object of class outside inheritance chain
=> #<AnyMethod:0xa00dc50>
  > @anym.global_method_anyclass # calling the method on object outside class hierarchy
Iam defined outside class or module at top of the file

2 => Instance methods :

  1. defined within a class with def keyword
  2. can be called only on instance i,e object of class within which it is defined or object of the inherited class
  3. can’t we called on class as its receiver

 

The above points can be illustrated with below output :

@method_demo = MethodDemo.new
=> #<MethodDemo:0xa015d4c>
>@method_demo.iam_instance_method
I can be exicuted only on object of my class
> MethodDemo.iam_instance_method
NoMethodError: undefined method `iam_instance_method’ for MethodDemo:Class

3 => Class methods :

  1. defined with self keyword
  2. the class method is singleton to its class i,e associated with class not to its instance
  3. it can be called with the class name in which it is defined
  4. can’t be invoked on object of the class

 

The above points can be illustrated with below output :

> MethodDemo.iam_class_method # calling the method on calss name
I can be exicuted on my class, not on its object
> @method_demo = MethodDemo.new
=> #<MethodDemo:0x9571ecc>
> @method_demo.iam_class_method # calling the method on object of class MethodDemo
NoMethodError: undefined method `iam_class_method’ for #<MethodDemo:0x9571ecc>

4 => Alias method :

  1. alias methods are created with alias or alias_method keyword. both behave same , but differ internally in terms of interpretation of method name. when we write alias :new :old (see there is no comma between the two method name), alias treat new and old as function name. similarly alias_method :new, :old (here comma between the two name) treat new and old as method name. But you can also write alias_method in another way alias_method new, old . In this case new and old are not method name, but variables name which contain the name of the method to be aliased. Thus this allow you to do the aliasing dynamically i,e you can store any name in new and old.
  2. The syntax is alias :new_name :current_name (no comma between literals) , alias_method :new_name, :current_name (comma between literal), alias_method new_name, current_name (new_name, current_name are variables)
  3. alias methods are synonymous to each other. see that both the aliased method i_will_be_aliased and aliase_method return the same output as the old method. basically, Aliases are often used to provide synonyms for method names. For instance, :size may be aliased to :length. This allows the programmer to use method names which “read” more naturally in a given context
  4.  Aliasing is also used to create a method which wraps the method of the same name by performing its own computations then calling the original method. We have seen this in the output of to_i above. the to_i method of string return 0 if the string is not a number. We have reopen the string class and redefined to_i method to raise exception if the string do not contain any number and perform the usual task if pass the test.
  5. In alias :new_name :current_name , the current_name function must be already defined. If the new_name function is already defined, it will be overwritten. NOTE : the new_name function will behave as current_name function at the time of aliasing, even if the current_name function is modified subsequently. for example after opening the string class, we have modified the original to_i function, but since before that we have aliased it to name old_to_i, this will always exhibit the original behaviour of to_i

 

The above points can be illustrated with below output :

> @method_demo = MethodDemo.new
=> #<MethodDemo:0x9665b08>
> @method_demo.i_will_be_aliased #calling the original method
you can create aliase of any method
> @method_demo.aliase_method # calling the old method with the new name
you can create aliase of any method # output is of the original class, the aliased method always point to original method even when the original get modified along the running program
> “arun”.to_i # calling to_i on arun string we have overridden in the String class
RuntimeError: No digits found # we have redefined the to_i method of ruby String class, so it is giving output as per its new defination
> “arun2″.to_i # since now the sring contain a number 2, it is giving 0 as expected
=> 0
> “arun”.old_to_i # we have aliased old_to_i to to_i, so the old_to_i method still point to the original to_i method, so not raising exception even when the string do not contain any number
=> 0

5 => Instance Singleton method

  1. it is associated with a single object of a class and can be called only on it. Any other object will throw nNoMethodError
  2. it is defined with syntex def @object_name.method_name

 

The above points can be illustrated with below output :

> @method_demo_singleton.only #calling the only method on object @method_demo_singleton
only method is availabe only to object @method_demo_singleton
> @method_demo = MethodDemo.new # creating new object of class MethodDemo
=> #<MethodDemo:0x96de530>
> @method_demo.only
NoMethodError: undefined method `only’ for #<MethodDemo:0x96de530> # error thrown as the method is singleton to @method_demo_singleton object not any other object of MethodDemo class.

6 => Return in method :

  1. return is used to pass back the control to the caller at the point is called irrespective of the fact that the whole code is executed or not
  2. explicit call of return cause the program to terminate prematurely . see that “I want to get exicuted” not called in explict use of return
  3. return can cause one or more value to return, in case of more then one value, it is returned as a array
  4. If no return is used, implicitly the value of last executed line is returned

 

The above points can be illustrated with below output :

> @method_demo = MethodDemo.new
=> #<MethodDemo:0x96f3070>
> @method_demo.demo_implicit_return
I want to get exicuted
=> “Arun”
> @method_demo.demo_explicit_return
=> ["santosh", "kapil"]

About these ads

Author: arunyadav4u

over 5 years experience in web development with Ruby on Rails.Involved in all stage of development lifecycle : requirement gathering, planing, coding, deployment & Knowledge transfer. I can adept to any situation, mixup very easily with people & can be a great friend.

2 thoughts on “methods in ruby

  1. Your means of describing the whole thing in this article is truly nice, every one
    be capable of easily be aware of it, Thanks a lot.

  2. Awesome! Its genuinely amazing article, I have got much clear idea concerning from
    this paragraph.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.