Hashes, Arrays, Ranges, and Sets all include a Ruby module called Enumerable.
Enumerable provides these data structures with a number of useful methods such as
In the following code, you can see some of these functions being used on an array:
x = (1..5).collect{ |i| i } p( x ) #=> [1, 2, 3, 4, 5] # ww w. j a va2 s . co m arr = [1,2,3,4,5] y = arr.collect{ |i| i } p( y ) #=> [1, 2, 3, 4, 5] z = arr.collect{ |i| i * i } p( z ) #=> [1, 4, 9, 16, 25] p( arr.include?( 3 ) ) #=> true p( arr.include?( 6 ) ) #=> false p( arr.min ) #=> 1 p( arr.max ) #=> 5
These same methods are available to other collection classes too, as long as those classes include Enumerable.
Here's an example using the Hash class:
h = {'one'=>'1', 'two'=>'2', 'three'=>'3', 'four'=>'4'} y = h.collect{ |i| i } # w w w. j a va2 s . c o m p( y ) p( h.min ) #=> ["one", "1"] p( h.max ) #=> ["two", "2"]