Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Ruby: Metaprogramming: Method that makes methods

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 375
    Comment on it

    Ruby: Meta Programming: Method that makes Methods


    Hi friends,
    The normal way of defining method is to give the method name after def and write code between def .... end, and it is pretty fine for most of the cases, but sometimes suppose we need something like, we want to have three different outputs for 3 types of users, where the method works for just specifying one string for them. and remaining code always remains same. Let's see the code here:

    
    	class User
    	  def validate_doctor arg
    	  	"doctor is #{arg}"
    	  end
    	 
    	  def validate_patient arg
    	    "patient is #{arg}"
    	  end
    	  
    	  def validate_guest arg
    	    "guest is #{arg}"
    	  end
    	end
    	 
    	user = User.new
    	puts user.validate_doctor("active")
    	puts user.validate_patient("inactive")
    	puts user.validate_guest("active")
    
    	#=> Output
    	doctor is active
    	patient is inactive
    	guest is active
    
    

    So as we see here we made 3 methods just for doing a same task, only one thing the type of the user we are changing everytime, that also we can retrieve from the method name itself. So rails allows you to define method like this where you can define multiple methods together using arguments:

    
    	class User
    	  	["doctor", "patient", "guest"].each do |action|
    		  	define_method("validate_#{action}") do |arg|
    				"#{action.gsub('_', ' ')} is #{arg}"
    	  		end
    	  	end
    	end
    	 
    	user = User.new
    	puts user.validate_doctor("active")
    	puts user.validate_patient("inactive")
    	puts user.validate_guest("active")
    
    	#=> Output
    	doctor is active
    	patient is inactive
    	guest is active
    
    

    So thus we have defined 3 methods as one in a single line. Here we have only 3 methods but suppose we have thousands of elements in this array that will gives us thousands of methods. It is nice, as we have written code here, that is generating code for us.

    Hope you liked reading this blog. For more like this Click here.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: