From 2ff81cf37b7f04c840c230706578cddd71053a18 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Mon, 10 May 2010 13:19:09 -0300 Subject: [PATCH] Allow Array to use his private rand method [#4555 state:committed] --- .../active_support/core_ext/array/random_access.rb | 6 ++++-- activesupport/test/core_ext/array_ext_test.rb | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/array/random_access.rb b/activesupport/lib/active_support/core_ext/array/random_access.rb index 343003f..b90fc63 100644 --- a/activesupport/lib/active_support/core_ext/array/random_access.rb +++ b/activesupport/lib/active_support/core_ext/array/random_access.rb @@ -1,6 +1,8 @@ class Array + alias_method :private_rand, :rand + # Returns a random element from the array. - def rand - self[Kernel.rand(length)] + def rand(value = nil) + value.nil? ? self[Kernel.rand(length)] : private_rand(value) end end diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb index e761746..1080fb6 100644 --- a/activesupport/test/core_ext/array_ext_test.rb +++ b/activesupport/test/core_ext/array_ext_test.rb @@ -367,6 +367,8 @@ class ArrayExtRandomTests < Test::Unit::TestCase Kernel.expects(:rand).with(3).returns(1) assert_equal 2, [1, 2, 3].rand + + assert_equal 0, [].rand(1) end end -- 1.7.1