I recently found that dynamically creating object and methods in Ruby is quite a work, this might be because of my background experience in Javascript.
In Javascript you can dynamically create object and it’s methods as follow:
function somewhere_inside_my_code() {
foo = {};
foo.bar = function() { /** do something **/ };
};
How is the equivalent of accomplishing the above statements in Ruby (as simple as in Javascript)?
You can achieve this with singleton methods. Note that you can do this with all objects, for example:
which will output:
These methods are really only defined on this single object (hence the name), so this code (executed after the above code):
just throws an exception: