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:
str = "I like cookies!"
def str.piratize
self + " Arrrr!"
end
puts str.piratize
which will output:
I like cookies! Arrrr!
These methods are really only defined on this single object (hence the name), so this code (executed after the above code):
str2 = "Cookies are great!"
puts str2.piratize
just throws an exception:
undefined method `piratize' for "Cookies are great!":String (NoMethodError)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With