Robert Klemme wrote:
> On 12.04.2008 07:50, Joel VanderWerf wrote:
>> Martin DeMello wrote:
>>> On Fri, Apr 11, 2008 at 2:17 AM, Pokkai Dokkai 
>>> <bad_good_lion / yahoo.com> wrote:
>>>> how to create random object  to a particular ruby object ?
>>>>
>>>>  for example i want like this
>>>>
>>>>  rand(Fixnum)   --> 345 (randomly)
>>>>  rand(Float)    --> 3877.5545(randomly)
>>>>  rand(String)   --> "sfskgksf" (randomly)
>>>>  rand(boolean)  --> 0(randomly)
>>> The cleanest way is to add the class method make_random to all your
>>> classes. For example
>>
>> Here is the dirtiest, wrongest, ugliest way to do it:
>>
>> module ObjectSpace
>>    def self.random_object(klass)
>>      n = each_object(klass){}
>>      i = rand(n)
>>      each_object klass do |obj|
>>        if i == 0
>>          return obj
>>        else
>>          i -= 1
>>        end
>>      end
>>      return nil
>>    end
>> end
>>
>> 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" ;)

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

-- 
       vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407