Class: Array
- Defined in:
- lib/kitchensink/patches/array.rb,
lib/kitchensink/patches/array.rb,
lib/kitchensink/patches/array.rb,
lib/kitchensink/patches/array.rb,
lib/kitchensink/patches/array.rb,
lib/kitchensink/patches/array.rb,
lib/kitchensink/patches/array.rb
Instance Method Summary collapse
-
#hash_by(attribute) ⇒ Object
Construct a hash of objects, keyed by some object attribute.
-
#product ⇒ Object
Multiplies all elements of an array together: * [2,3,4].product => 24 * [2.0, 3.0, 4.0].product => 24.0 * [“NO”, 3, 2].product => “NONONONONONO”.
-
#rand_index ⇒ Object
returns a random index from this array.
-
#rand_value ⇒ Object
returns a random value from this array.
-
#shuffle ⇒ Object
Returns an array with its elements shuffled.
-
#shuffle! ⇒ Object
Returns an array with its elements shuffled.
- #sum ⇒ Object
Instance Method Details
#hash_by(attribute) ⇒ Object
Construct a hash of objects, keyed by some object attribute.
Original idea and code by Brian Dainton. Taken from his blog, The Budding Rubyist. buddingrubyist.wordpress.com/2008/02/05/why-i-like-to-inject/
7 8 9 10 11 12 |
# File 'lib/kitchensink/patches/array.rb', line 7 def hash_by(attribute) inject({}) do |results, obj| results[obj.send(attribute)] = obj results end end |
#product ⇒ Object
Multiplies all elements of an array together:
-
[2,3,4].product => 24
-
[2.0, 3.0, 4.0].product => 24.0
-
[“NO”, 3, 2].product => “NONONONONONO”
22 23 24 |
# File 'lib/kitchensink/patches/array.rb', line 22 def product inject {|product,element| product*element} end |
#rand_index ⇒ Object
returns a random index from this array
31 32 33 |
# File 'lib/kitchensink/patches/array.rb', line 31 def rand_index rand(size) end |
#rand_value ⇒ Object
returns a random value from this array
40 41 42 |
# File 'lib/kitchensink/patches/array.rb', line 40 def rand_value self[rand(size)] end |
#shuffle ⇒ Object
Returns an array with its elements shuffled. Uses algorithm from Ruby Cookbook 4.10
74 75 76 |
# File 'lib/kitchensink/patches/array.rb', line 74 def shuffle self.dup.shuffle! end |
#shuffle! ⇒ Object
Returns an array with its elements shuffled. Uses algorithm from Ruby Cookbook 4.10
63 64 65 66 67 68 |
# File 'lib/kitchensink/patches/array.rb', line 63 def shuffle! each_index do |i| j = rand(length-i) + i self[j], self[i] = self[i], self[j] end end |