Maybe this is a stupid idea… I am new to Ruby (and to OOP, so I still dont really know what I am doing most of the time), and I thought of a small, fun project to build, and I am struggling with some concepts.
What I am building is basically a string manipulator. I am building a module with extra methods, and then including that on the String class.
My module has several methods that manipulate the strings in different ways, mostly replacing words, and then return the modified string.
What I want to do in order to make the string manipulation more ‘spontaneous’ and natural, is to create a “main” method (the one I will be calling from the strings), that randomly selects one of the string manipulation methods, and then returns the string (and then can be called again to apply several manipulations in one go)
How can I do this, or something similar? Hope I explained myself
Thanks
O.
Here’s the random manipulation module, as you described it.
something_randomis the main method:Mix it into
String:Now we can create an empty string, and then do something random to it a few times, printing it out each time:
There are two bits that are interesting. The first is this:
That removes
:something_randomfrom the arraymethods, preventing the *something_random* method from calling itself. The second interesting bit is this:Array.sample(Ruby >= 1.9) selects a random method.sendthen dispatches that method. In Ruby 1.8, do this instead: