2009/6/30 Brian Candler <b.candler / pobox.com>:
> Lloyd Linklater wrote:
>> function GetRandomChar: char;
>> var
>> r: integer;
>> begin
>> r := random(36);
>> case r of
>> 0..25: result := chr(ord('a') + r);
>> else : result := chr(ord('0') + r);
>> end;
>> end;
>
> In this case, you can just do:
>
> def get_random_char
>  䨳󨳶
> end
>
> Since Ruby allows arbitrary bignums, you can also get strings this way
> too. e.g. for an 8-digit string:
>
>  䨳  󨳶
Interesting idea!  Does rand have enough precision to fill arbitrary
large numbers?

> However there's a bug there, because numbers with one or more leading
> zeros will be truncated. How to left-pad a non-decimal number with zeros
> isn't actually that obvious. Maybe someone can point out something
> simpler than this:
>
> "0"*8 + rand(36 ** 8).to_s(36))[-8..-1]
>
> (Unfortunately, "%08s" as a format string pads with spaces not zeros)

irb(main):012:0> "e".rjust 10, "0"
=> "000000000e"
irb(main):013:0>

Kind regards

robert


-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/