diff --git a/NEWS b/NEWS index 00d685f..13facea 100644 --- a/NEWS +++ b/NEWS @@ -79,6 +79,8 @@ with all sufficient information, see the ChangeLog file. * Random * extended method: * Random.rand supports range argument + * new method: + * Random.bytes * String * extended method: diff --git a/random.c b/random.c index 0cffbab..4d2be4c 100644 --- a/random.c +++ b/random.c @@ -964,6 +964,18 @@ rb_random_bytes(VALUE obj, long n) return bytes; } +/* + * call-seq: Random.bytes(size) -> a_string + * + * Returns a random binary string. The argument size specified the length of + * the result string. + */ +static VALUE +random_s_bytes(VALUE obj, VALUE len) +{ + return random_bytes(rb_Random_DEFAULT, len); +} + static VALUE range_values(VALUE vmax, VALUE *begp, VALUE *endp, int *exclp) { @@ -1346,6 +1358,7 @@ Init_Random(void) rb_define_singleton_method(rb_cRandom, "srand", rb_f_srand, -1); rb_define_singleton_method(rb_cRandom, "rand", random_s_rand, -1); + rb_define_singleton_method(rb_cRandom, "bytes", random_s_bytes, 1); rb_define_singleton_method(rb_cRandom, "new_seed", random_seed, 0); rb_define_private_method(CLASS_OF(rb_cRandom), "state", random_s_state, 0); rb_define_private_method(CLASS_OF(rb_cRandom), "left", random_s_left, 0); diff --git a/test/ruby/test_rand.rb b/test/ruby/test_rand.rb index 9ba38f3..961a90f 100644 --- a/test/ruby/test_rand.rb +++ b/test/ruby/test_rand.rb @@ -340,10 +340,14 @@ END end def test_random_bytes + srand(0) r = Random.new(0) assert_equal("", r.bytes(0)) + assert_equal("", Random.bytes(0)) assert_equal("\xAC".force_encoding("ASCII-8BIT"), r.bytes(1)) - assert_equal("/\xAA\xC4\x97u\xA6\x16\xB7\xC0\xCC".force_encoding("ASCII-8BIT"), r.bytes(10)) + assert_equal("\xAC".force_encoding("ASCII-8BIT"), Random.bytes(1)) + assert_equal("/\xAA\xC4\x97u\xA6\x16\xB7\xC0\xCC".force_encoding("ASCII-8BIT"), r.bytes(10)) + assert_equal("/\xAA\xC4\x97u\xA6\x16\xB7\xC0\xCC".force_encoding("ASCII-8BIT"), Random.bytes(10)) end def test_random_range