Overriding the Private Method of a Ruby Class

It feels like forever since I ever posted anything, but, here I am with an interesting post on ruby! Consider the following class which has a private method called “say”.

class Client
   def print
      say
   end

   private
      def say
          "hello"
      end
end

c = Client.new
puts c.print

Let’s assume you are unit testing the Client class and you want to override the say. But, why would you want to override the said method? There are numerous reasons – for one, the say method could talk to a web service to get some data to be used by one of the public methods. For unit tests, it’s better to have some predictable data rather than have something that would change quite often, rendering the unit tests useless!

So, under the assumption that the data will always be available using a specific format we can override this private method as shown below:

class Client
    def self.print
       new.print
    end

    def print
       say
    end

    private
        def say
           "hello"
        end
end

c = Client.new
puts c.print

puts "=========="

k = Class.new(Client) do
    define_method(:say) do
        "hello from an overridden private method"
    end
end

puts k.print

puts "=========="

k_instance = k.new
puts k_instance.print

Since this is not an introduction to ruby classes :) , I am going to make this quick! Lines 21 to 25 are of prime interest. Ruby’s Class.new class method is used to create a new class by passing the class in question – Client. Then using the define_method method I pass in a method name :say and define what it’s supposed to do – in this case return a different string instead of the one defined in the Client class.

That’s it! You can also create an instance of the newly defined class as shown in line 31! Calling the print method would display the following:

hello
==========
hello from an overridden private method
==========
hello from an overridden private method

Line 1 displays what will be printed without any overrides. Line 3 displays what will be printed when the class method is called after the say method is overridden by Class.new returns a new class and line 5 displays the same as line 3, but this time with an instance created using the class returned, again by Class.new

Share

IronRuby – A Wrapper to Execute ruby code using C#

It’s been quite a while since I posted! So, lets have some fun. In this post I am going to present to you something experimental (not path breaking by any means!) I was doing with IronRuby. I wanted to create a wrapper for IronRuby, so that I don’t have to have a lot of repetitive code to execute some ruby code within .net using the new DLR. Before getting to that, let me give a quick outlook of executing ruby code in C#. The .net world has an equivalent to ruby called as “IronRuby”. Before getting started, we need the references for IronRuby. Download them from the IronRuby site (here) and add references to the following dll’s in your project. In this example I am using the 1.1.3 (download link) version of IronRuby in this post.

  • IronRuby.dll
  • IronRuby.Libraries.dll
  • Microsoft.Scripting.dll

After this step you are ready to go the ironruby way! IronRuby, being a dynamic language uses the DLR (Dynamic Language Runtime). In order to execute ruby code in .net, you first need to create a runtime object using the CreateRuntime method in the Ruby class. Using this runtime, you then have to create a ruby engine using the GetEngine method of the ScriptEngine. Note that you have to pass the engine type "rb".

Note: Similarly if you have references to IronPython (.net equivalent of python), you can follow similar steps to create an engine for python. So in this case GetEngine‘s parameter would be "py" to create a IronPython script engine.

Once you create the ScriptEngine object, you are ready to execute any ruby script and in case they have classes, you can even instantiate an instance in .net and call their methods. Following is the fully working code that executes some ruby code to just print some text and also to register a class with the DLR. In order to get familiar with the DLR an important keyword to understand is the dynamic keyword. Let’s understand this keyword before I get in to the remaining details

public static void Main(string[] args)
{
    Console.Write("Loading sample.rb...\n\n");

    ScriptRuntime rb = Ruby.CreateRuntime();
    ScriptEngine engine = rb.GetEngine("rb");
    engine.Execute("puts 'This is a test'");

    var rbPerson = engine.Execute(@"class Person
				    def greet()
					puts 'Hello world!'
				    end
				    end");

    object persInst = engine.Runtime.Globals.GetVariable("Person");
    dynamic person = engine.Operations.CreateInstance(persInst);
    person.greet();
}

.Net framework 4 introduced the dynamic keyword. Most important thing about dynamic is that is bypasses type checking. It has other purposes too, but we are mainly concerned about the uses in the perspective of dynamic languages. In this case, I use dynamic variables to hold instances of classes created. Thus, as there is no type checking, intellisense wouldn’t work with the variables of type dynamic.

Now, let me dwelve more in to the above sample. Lines 5 & 6, create a ruby runtime object and then creates a ruby engine using theis runtime object. After this point, the engine created can be used to execute ruby code. Line 7′s results can be immediately seen as it’s a call to the put method of ruby which prints the string passed. So line 7 would just print the message. But lines 9 – 13 are interesting. These lines execute the code that defines a class. So this wouldn’t produce any output. In order to use/create an instance of Person, first you need to create a reference to the person variable (Person is also a variable) using the GetVariable method of the Globals object in the engine’s runtime. Once you have a reference to this variable, an “instance” of Person can be created, using the CreateInstance method of the Operations object, again belonging to the engine object we created earlier.

Following is the output when the above code is ran.

Loading sample.rb...

This is a test
Hello world!
Press any key to continue . . .

Now, lets get to the most important part of this post. As I said before, I created a wrapper around the concept I explained. Whenever I want to create an instance (or add a script), I don’t want to repeat the steps listed earlier. Because, whenever an instance is required, if it doesn’t exist, we have to to execute the ruby script.

Taking care of this also would require managing a set of variables. To free myself from all these nuances, I created the following wrapper. I am just going to explain the most important parts. This wrapper contains the RubyExecutor class, which is responsible for managing the adding and the executing of the ruby scripts. This class inherits from the ExecutorBase class which takes on the entire load of taking care of stuff. It contains 2 abstract methods CreateRuntime and CreateEngine which the RubyExecutor overrides to create the ruby runtime and the engine (It will be evident why these methods are abstract in the following sections). Also there is a virual method called Init which need not overridden in the derived class. Apart from this a variable isInitialize is used to keep track of the state of the object. In this case it stores whether the object has been initialized. When a user instantiates an instance of RubyExecutor the base class’s ExecuteAll method is called. This executes all the scripts added using the AddScript and AddFile methods and then sets the isInitialized variable to true. After this point, the RubyExecutor instance can still be used to add scripts or files, but only the new ones will be executed by the engine.

public abstract class ExecutorBase
{
	private bool isInitialized = false;

	protected ScriptRuntime scriptRuntime;
	protected ScriptEngine scriptEngine;
	protected List<DynamicLanguageScript> scriptList;

	protected abstract void CreateRuntime();
	protected abstract void CreateEngine();

	public void Init()
    {
	    ExecuteAll();
    }

	public ExecutorBase()
	{
	    InitiateSequence();
	}

	private void InitiateSequence()
	{
	    scriptList = new List<DynamicLanguageScript>();
	    CreateRuntime();
	    CreateEngine();
	}

	public void AddScript(string scriptContents)
	{
	    scriptList.Add(new DynamicLanguageScript { CodeText = scriptContents, Executed = false });

	    if (isInitialized)
		    ExecuteRecent();
	}

	public void AddFile(string scriptFile)
	{
	    scriptList.Add(new DynamicLanguageScript { CodeText = ReadFile(scriptFile), Executed = false });

	    if (isInitialized)
		    ExecuteRecent();
	}

	protected void ExecuteAll()
	{
	    scriptList.ForEach(s => { scriptEngine.Execute(s.CodeText); s.Executed = true; });
	    isInitialized = true;
	}

	protected void ExecuteRecent()
	{
	    scriptList.Where(s => !s.Executed).ToList().ForEach(s => { scriptEngine.Execute(s.CodeText); s.Executed = true; });
	}

	public object GetInstance(string instanceName)
	{
	    if (!isInitialized)
		    throw new NotSupportedException("Executor not initialized. Call \"Init()\" to initialize");

	    dynamic instanceVariable;
	    var instanceVariableResult = scriptEngine.Runtime.Globals.TryGetVariable(instanceName, out instanceVariable);            

	    if (!instanceVariableResult && instanceVariable == null)
		    throw new InvalidOperationException(string.Format("Unable to find {0}", instanceName));

	    dynamic instance = scriptEngine.Operations.CreateInstance(instanceVariable);
	    return instance;
	}

	public IEnumerable<string> GetInstanceNames()
	{
	    return scriptEngine.Runtime.Globals.GetVariableNames();
	}

	public bool CanInstantiate(string className)
	{
	    return scriptEngine.Runtime.Globals.ContainsVariable(className);
	}

	private string ReadFile(string fileName)
	{
	    if (File.Exists(fileName))
	    {
		    return File.ReadAllText(fileName);
	    }
	    throw new FileNotFoundException(string.Format("{0} was not found", fileName));
	}
}

public class RubyExecutor : ExecutorBase
{
	protected override void CreateRuntime()
	{
	    scriptRuntime = Ruby.CreateRuntime();
	}

	protected override void CreateEngine()
	{
	    scriptEngine = scriptRuntime.GetEngine("rb");
	}
}

public class DynamicLanguageScript
{
	public string CodeText { get; set; }
	public bool Executed { get; set; }
}

Line 7 and lines 56 – 69 is of prime importance in this wrapper. Line 7 declares a list of DynamicLanguageScript which is used to hold a reference to any file or script added and also whether or not it was executed. Lines 59 to 69 is the most important method for this wrapper GetInstance. Once the wrapper is initialized, users can call this method to get an instance of any class defined in the scripts/files added. So, let’s dig in to this method in detail.

public object GetInstance(string instanceName)
{
    if (!isInitialized)
	    throw new NotSupportedException("Executor not initialized. Call \"Init()\" to initialize");

    dynamic instanceVariable;
    var instanceVariableResult = scriptEngine.Runtime.Globals.TryGetVariable(instanceName, out instanceVariable); 

    if (!instanceVariableResult && instanceVariable == null)
	    throw new InvalidOperationException(string.Format("Unable to find {0}", instanceName));

    dynamic instance = scriptEngine.Operations.CreateInstance(instanceVariable);
    return instance;
}

In the above code snippet, when the method is called, I first check if the wrapper is initialized. Without initialization, the scripts are not executed and so I just throw and exception. If initialized, I use the dynamic keyword to declare a placeholder for the instance of the ruby object that would be created. Then, using the script engine’s Runtime method, I access the Globals instance and call the TryVariable method. This method looks at the scripts executed and tries to find a class definition. If available, I use the CreateInstance method defined within the Operations object (using the script engine) to create an instance of the name of the variable passed and return it. Enough said, let’s see an example of how this wrapper could be used.

To begin with, create an instance of the ruby executor (rExecutor). The AddScript method is then called to add a script which has the definition for a class named Person. Then I call the Init method to initialize the wrapper. From this point, the wrapper can be used to create instances of Person. To do this, I use the GetInstance method in line 12. Now, using this instance I can call the methods for the instance, for example the say method, which would just print the message “Hello”. Following this in the snippet below, there are more examples of how this wrapper could be used.

public static void Main(string[] args)
{
    Console.Write("Creating an instance of ruby executor...");
    RubyExecutor rExecutor = new RubyExecutor();
    Console.Write("done");
    Console.WriteLine();

    rExecutor.AddScript(@"class Person
			    def say
				puts ""Hello""
			    end
			   end");
    rExecutor.Init();

    dynamic inst = rExecutor.GetInstance("Person");
    inst.say();

    Console.WriteLine();

    foreach(var name in rExecutor.GetInstanceNames())
	Console.WriteLine(name);

    Console.WriteLine();

    if (rExecutor.CanInstantiate("Person"))
    {
	   dynamic inst2 = rExecutor.GetInstance("Person");
	   inst2.say();
    }

    Console.WriteLine();

    if (rExecutor.CanInstantiate("Person2"))
    {
	   dynamic inst2 = rExecutor.GetInstance("Person2");
	   inst2.say();
    }
    else
    {
	   Console.WriteLine("Can't instantiate \"Person2\"");
    }

    rExecutor.AddScript(@"class Testclass
			    def run
				puts ""The sum of 1 & 2 is #{1+2}""
				p = Person.new
				p.say
			    end
			   end");
    dynamic instTest = rExecutor.GetInstance("Testclass");
    instTest.run();
}

The output produced when running the above snippet is given below:

Creating an instance of ruby executor...done
Hello

Person

Hello

Can't instantiate "Person2"
The sum of 1 & 2 is 3
Hello
Press any key to continue . . .

To follow up, you could also create a PythonExecutor for dealing python scripts. It would work similar to the ways of the RubyExecutor. But, in this post I am not going to discuss about python, because it’s not really my forte!

public class PythonExecutor : ExecutorBase
{
	protected override void CreateRuntime()
	{
	    scriptRuntime = Python.CreateRuntime();
	}

	protected override void CreateEngine()
	{
	    scriptEngine = scriptRuntime.GetEngine("py");
	}
}

Downloads – RubyExecutor.cs and RubyExecutorVerifier.cs (rename to .cs)

Hope this post was interesting!

Share

Yet Another Ruby Language Post :)

This time, I am back with a post that deals with few interesting aspects of ruby. To begin with, I am going to discuss about YAML (Guess you now know the reason why I gave this title to this post :D ). YAML is an acronym for Yet Another Markup Language. YAML is a way by which data could be serialized in a human readable format. In ruby’s context, YAML could be used to save the state of ruby objects. Ruby makes it really easy to store and retrieve YAML objects. This enables you to accomplish things with a very few lines of code. Conside the following for example:

require 'yaml'
a =['a', 'b']
y(a)

In order to use YAML in ruby, you need to import the YAML library. This is done using the require statement. Then I declare a simple ruby array called ‘a’. Now y is a method from the YAML library that prints the array ‘a’ in the YAML format. The output is given below. The first line --- indicates that this is a YAML serialized data. Then the following lines represent every entry in the array.

---
- a
- b

This technique could also be utilized for saving the state of an instance or a list of instances. Consider the following class and an instance of it.

class Appdata
	attr_accessor :id, :title, :description

	def initialize(p_id, p_title, p_description)
		@id = p_id
		@title = p_title
		@description = p_description
	end
end

i = Appdata.new(1, "Title 1", "Description 1")
y(i)

Executing this snippet would give the following output. The first line as before indicates that this is a YAML serialized data. After —, !ruby/object:Appdata indicates that what follows is an instance of the Appdata object. Following this line, every property of this instance is listed.

>ruby variables.rb

--- !ruby/object:Appdata
description: Description 1
id: 1
title: Title 1
>Exit code: 0

This could very well be put in to a number of useful implementations. For example, an application’s configuration/state could be stored/retrieved using this. Consider the class given below:

require 'yaml'

class Dataclass
	attr_writer :data_id, :data_name

	def initialize(id, name)
		@data_id = id
		@data_name = name
	end

	def getdataid
		@data_id
	end

end

a = Dataclass.new(3,"three")

if (!File.exists?("app_state.config"))
	puts "Dumping app state"
	f = File.new("app_state.config", 'w')
	YAML.dump(a, f)
	f.close
end

$config

if (File.exists?("app_state.config"))
	puts "Reading app state"
	File.open("app_state.config") { |data|
		$config = YAML.load(data)
	}
end

puts $config.getdataid

In the above listing, lines 3 – 15 represent the config class I wish to save. Line 17 creates an instance of Dataclass. Lines 19-24 checks if there is a file named “app_state.config” and if not it creates a new file with the same name and then uses the YAML.dump method to dump the instance a in to the file created using the handle f. Then to demonstrate the fact that this serialized data can be loaded back, I am using the YAML.load method. This is demonstrated using lines 28 – 33. Before this, I have defined a variable $config to store the configuration object stored. In order to do this, the file is opened using the File.open method. The data read from the file is made available to the block that will executed after the read operation using the |data| variable. Then I call YAML.load method to load the Dataclass instance in to the $config variable.

From this point onwards, $config can be used in the application as shown in line 35. I have put YAML in to use in my to-do list application. I use YAML to save / load tasks added by the user. Check out this file to see what I mean. A sample file generated by this application is here.

This greatly simplifies the amount of code required to do this. This is evident when you compare the amount of code involved in text manager which save’s / load’s the tasks in to a text file. Code for this is here. A sample file generated by this application is here.

The next thing I would like to discuss is about class & instance variables and class methods. When I was getting myself acquainted with ruby, I was stumped once even though I knew the difference between a class and instance variable, as it didn’t register well enough in my mind. After identifying the mistake it’s going to be etched forever in my memory! To begin with, in ruby, an instance variable is prefixed with ‘@’ and a class variable is prefixed with ‘@@’. A class method is similar to a c# static method and so an instance is not required to call this method. So, a class variable is similar to a static field.

I am sure you are aware about classes and objects. A class is a blueprint of an object, it’s a collection of properties (representing state) and methods (representing behavior). And, an object is an instance of a class. Every instance variable is specific to an instance as the name suggests and a class variable is common across all the instances and so is specific to the class. Let me make it clear with an example.

class Sampleclass
	@@no_instances = 0

	attr_accessor :initialMessage 

	def initialize(initMessage)
		@@no_instances = @@no_instances + 1
		@initialMessage = initMessage
	end

	def print
		puts "Hello from Sampleclass #{self.inspect}"
	end

	def Sampleclass.printInstanceCount
		puts @@no_instances
	end
end

In the above snippet, line 2 represents a class variable and line 4 represents an instance variable. And line 15 represents a class method, which is similar to a C# static method. A ruby class method, just like other instance methods, starts with the def keyword. Then the method is named in the format ClassName.MethodName as shown in the snippet above. In this case, @@no_instances is used to maintain a count of the number of instances of Sampleclass created so far. The class method in this case is used to print the number of instances created for this object. Line 2 initializes the class variable to 0. Whenever an instance of Sampleclass is created, this counter is incremented. Notice that it is not reset for every instantiation of this class. The class method provides a way by which the user can get to know the number of instances created so far. The snippet below demonstrates this.

a = Sampleclass.new("Hello")
a.print

b = Sampleclass.new("Hello")
b.print

Sampleclass.printInstanceCount

c = Sampleclass.new("Hello")
c.print

Sampleclass.printInstanceCount

When the above snippet is executed, the following is the output.

>ruby variables.rb
Hello from Sampleclass #<Sampleclass:0x5d8a78 @initialMessage="Hello">
Hello from Sampleclass #<Sampleclass:0x5d8988 @initialMessage="Hello">
2
Hello from Sampleclass #<Sampleclass:0x5d8898 @initialMessage="Hello">
3
>Exit code: 0

Notice lines 3 and 5, these are due to the calls to the class method and it displays the number of instances created. Hope this post was informative / refreshing!

Do post your comments!

Share

More ruby bits

It’s ruby time again! Just for fun (or may be it’s useful) I wanted to create a class that holds a list of similar objects. I wrote this class based on the following requirements:

  • Should enable the user to specify the type the list will hold during initialization
  • Should be able to hold an arbitrary amount of similar objects
  • Should provide a method to return all the items in the array
  • Should be able to return a single element
  • Should be able to invoke an operation using a block passed to the method on each object
class List
    def initialize (defType)
        @defaultType = defType

        if (!validate_type)
          raise "Invalid type parameter: unable to create an object of type #{@defaultType}"
        end

	@objArr = []
    end

    def add(someObj)
      @objArr.push(someObj) if (someObj.class.to_s.eql?(@defaultType))
    end

    def get
      return @objArr
    end

    def getitemat(pos)
      @objArr.at(pos.to_i)
    end

    def each(&block)
      @objArr.each{|item| block.call(item)}
    end

    private
    def validate_type
      type_validation_status = true
      begin
        type = Object::const_get(@defaultType).new()
      rescue
        type_validation_status = false
      end

      type_validation_status
    end
end

In the class above, the 1st requirement is satisfied using lines 2 – 10. When a user initializes this class, a type name has to be passed. Then validate_type method is called (More information related to this is here). This verifies if a type of the name passed can be created. If unable to create such a type, I throw and exception and quit. Else an array is initialized and the instance is now available for use. This along with lines 12 – 14, satisfies the 2nd requirement as a ruby array can hold any number of items (of course limited by memory available!). Note that the add method does not add the object passed if the object is not of type @defaultType.

Requirement 3 is satisfied by lines 16 – 18. The user can use this method (get) to get all the items and use a for loop to iterate over the list. getitemat method following the get method could be used to access a single item specified by the index passed.

The final requirement is satisfied by the each method. This method is interesting of the lot. It takes in a block as a parameter. Then I iterate over each of the item in the array and then invoke this block by passing the item as a parameter.

So, as explained, this class can be used to store a list of similar objects. The following is a sample of how this could be used:

class Sampleclass
  def print
    puts inspect
  end
end

class Sampleclass2

end

list = List.new("Sampleclass")

list.add(Sampleclass.new)
list.add(Sampleclass.new)
list.add(Sampleclass.new)

# this won't be added
list.add(Sampleclass2.new)

list.add(Sampleclass.new)
list.add(Sampleclass.new)

puts "Calling the print method of every instance of Sampleclass"

list.each{|a| a.print}

puts "\n"
puts "Getting a certain item from the list"

item = list.getitemat(2)
item.print

Here is a link to github with this file.

Ruby’s blocks are something that interests me anytime. This section discusses how you can return values from within a ruby block. Firstly, ruby blocks cannot contain return statements. You may also remember that in any method, ruby returns the result of the last evaluation of an expression. This is put in to use within a block to return values.

For instance, consider the ruby snippet below. exec method takes in a block as a parameter in this case (&block). The intention here is to make the block return a value to the calling method. In order to do this, you just have to make sure that the last expression evaluated is the result you wish to return. In this case the block takes in an integer and returns as answer the value obtained by multiplying with itself. Also, notice that within the block, this is last expression being evaluated.

def exec(&block)
  result = block.call(5)
  puts result
end

exec{ |x| x * x}

The result of the expression is now returned to the method that executed this block, and is stored in result.

Hope this post was interesting! Happy coding!!!

Share

Ruby bits

Okay, in this post I am going to discuss some interesting bits of ruby. To begin with, this is a very useful feature that you could utilize in ruby, in case you are writing a mini language based on certain rules for yourself. Let us assume you need to split string in to tokens. Yes this is easy, just write a regular expression to do this.

But, oops! Suddenly you notice that the input string can also contain strings in single or double quotes. With this requirement, writing regular expressions can be tedious. So as to solve this without much hassles, you can use the shellwords module of ruby which comes as a language feature. A smaple is given below:

# split words
require 'shellwords'

data = 'some "words within quotes" to \'split into parts\''
words = Shellwords::shellwords(data)
words.each{ |word| puts word }

In order to use shellwords, I have a require statement to begin with. Then I call shellwords, which is an alias for the shellspit method. The shellsplit method itself uses some funky regexes to split the data we passed in to constituent strings and returns an array. Note that in the resultant array, “words within quotes” and ‘split into parts’ are going to be single entries and not 3 entries.I am using this in my first ever (:)) major ruby project. This is a program to manage my to-do lists. As it is evident, this is a console based application. You can view it here

Next bit is another interesting thing in ruby. You might be familiar with the reflection assembly in .Net. It is used to dynamically create types from strings that represent a type in an assembly. The following method could be used in ruby to mimic the same. The following example demonstrates this. To begin with, I have a type (class) that is called SampleType, with a method print. Let us see how we can dynamically create this type.

class SampleType
  def print
      puts "printing from sample type"
  end
end

Assuming the class name is in a variable called, create_type, we just need to use the const_get method within the generic Object type. This is because in ruby all the types (classes) are “constants“. And a quick tip, ruby classes cannot have their names starting with a lower case character, because constants in ruby cannot have a lowercase character and classes are constants in ruby. After passing in the type (class) name (which is a string) to the const_get method, we call the new method to actually create an instance of the type. If a class does not exist by the specified name, the return value is going to be ‘nil‘. Once we successfully receive the instance of the type, the type’s instance methods can be called as shown in the example below.

# create type using a string
create_type = "SampleType"
type = Object::const_get(create_type).new()
type.print

Example given below is a slight variation of the previous example. In this case, the generated type has a constructor that expects a string parameter.

class SampleTypeWithParams
  def initialize(parameter)
    @param = parameter
  end

  def print
    puts "printing from sample type with the parameter #{@param}"
  end
end

create_type = "SampleTypeWithParams"

type = Object::const_get(create_type).new("a parameter")
type.print

I am putting this into use in the same to-do list project I was talking about earlier. Every activity in this project is managed by an individual type. Like ListTask to list the tasks, AddTask to add a task and so on. So instead of using if conditions on the command entered, I use this method to generate a type. If successfull, the responsibility is handed over to the created type which has a common method called ‘execute’. The sample is here.

If you are interested at all, here is the link for the todo-list project, which can be used to manage console based applications!

PS: I am a beginner in ruby, so please correct me in case anything I have said is incorrect! Thanks for reading and happy coding!

Share

Some ruby love! – method_missing

Okay, time for some ruby love :) At this point, ruby gets the first place among my favorite dynamic languages! In this post I would like to discuss some interesting ruby facts I learned recently. First post is about method_missing. method_missing is a special method in ruby that can be used to handle calls to non-existent methods. The signature is given below and it is required that the same signature is followed in case you wish to implement this method.

For more information about the parameters, see the inline comment in the code.

class Missingmethods
   # method_missing takes 3 parameters
   # @m: method's symbol name, use to_s to convert to a string
   # @*args: variable number of arguments passed to the method
   # @&block: a block of code to be executed
   def method_missing(m,*args,&block)
	puts "Not able to find the #{m} method"

       for i in args 	do
	       puts(i)
       end

        if block_given?
	       block.call
        end
   end
end

Missingmethods.new.someMethod(1,2) { puts "Some block" }

If you notice, in the above snippet, within the method_missing method, I first print the missing method’s name. Note that m is a symbol. Then I loop through the arguments and print them. Final statement is interesting. In order to execute the block passed, I check if a block was passed. Then I can invoke the ‘call’ method to execute the block passed. I am under the impression that yield can also be used in this case. Let me try that next!

If you execute the above snippet, you will see the following:

>ruby verify.rb
Not able to find the someMethod method
1
2
Some block
>Exit code: 0

A (more) complete example is available at github!

Happy coding!

Share