Is there a way to call methods of a certain class randomly in ruby?

I was wondering if something like this could be done:

class Something
  def A
    puts "A"
  end
  def B
    puts "B"
  end
  def C
    puts "C"
  end
  def D
    puts "D"
  end
end

y = Something.new
x = Random.new
x.rand(y)

      

then we get a random result of the class "Something"

+3


source to share


3 answers


One line answer:

Something.new.send(Something.instance_methods(false).shuffle.first)

      

Explaination

Something.instance_methods(false)
# Will give you [:A, :B, :C, :D]

Something.instance_methods(false).shuffle.first
# Will give you a random method out of it

Something.new.send(<method name>)
# Will call that random method and give you output

      



FROM COMMENTS (great suggestion)

You can use it like:

Something.instance_methods(false).sample

instead Something.instance_methods(false).shuffle.first

+4


source


If you really want to do this -

x.send(x.instance_methods(false).sample, y)

      



Now, of course, this won't work if the target method doesn't take an argument.

0


source


class Random
 def rand_method
  #instance_methods(false), gives methods as symbols that are only inside of Something
  Something.instance_methods(false).sample
 end
end


Random.new.rand_method # will give the random method

      

0


source







All Articles