How to create random object to a particular ruby object?

Joel VanderWerf wrote:

Martin DeMello wrote:

Here is the dirtiest, wrongest, ugliest way to do it:
but that is worked for me .

module ObjectSpace

p ObjectSpace.random_object(String)
p ObjectSpace.random_object(Float)

thank you to all

Robert K. wrote:

rand(String) --> “sfskgksf” (randomly)
each_object klass do |obj|
p ObjectSpace.random_object(String)
p ObjectSpace.random_object(Float)

This does not work well for Strings because you get only instances that
do exist already when the method is called. That way you a) have no
clear definition of what you get (length, contained chars…) and b) you
either need to dup or freeze the return value. Both have their
problems: #freeze has side effects and #dup does not work for all classes.

I did say “wrongest” :wink:

For floats, you usually get e, pi, or the max/min floats, if no other
floats have been instantiated.