Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to create a method that chooses a random method from that same class

Tags:

methods

oop

ruby

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.

like image 951
agente_secreto Avatar asked Dec 21 '25 06:12

agente_secreto


1 Answers

Here's the random manipulation module, as you described it. something_random is the main method:

module RandomStringManipulation

  def something_random
    methods = RandomStringManipulation.instance_methods
    methods -= [:something_random]
    send methods.sample    # Ruby >= 1.9 required.  See below for Ruby 1.8.
  end

  def foo
    self + "foo"
  end

  def bar
    self + "bar"
  end

end

Mix it into String:

class String
  include RandomStringManipulation
end

Now we can create an empty string, and then do something random to it a few times, printing it out each time:

s = ""
4.times do
  s = s.something_random
  p s
end

# => "foo"
# => "foobar"
# => "foobarbar"
# => "foobarbarfoo"

There are two bits that are interesting. The first is this:

methods -= [:something_random]

That removes :something_random from the array methods, preventing the *something_random* method from calling itself. The second interesting bit is this:

send methods.sample

Array.sample (Ruby >= 1.9) selects a random method. send then dispatches that method. In Ruby 1.8, do this instead:

send methods[rand(methods.size)]
like image 155
Wayne Conrad Avatar answered Dec 24 '25 12:12

Wayne Conrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!