User:Bhanutpt/scratchpad/ruby
Enumerators, Ranges, Arrays and Hashes
editEach of these can use the each method for iteration, though they seems to be synonyms, there is lot of difference in computing, The Enumerators and Ranges are almost of fixed memory length and so are memory efficient and fast, whereas Arrays and Hashes involves complex data structures for to be dynamic
Enumerators
edit5.times.class # => Enumerator
5.upto(10).class # => Enumerator
5.upto(10).next # => 5
Ranges
edit(0...10).class # => Range
(0..9).class # => Range
(1..5).next # invalid, Range class doesent have next method
Arrays
editAn array is a collection of elements, by default an array of n elements has its index enumerated from 0 to n-1, i.e, the index to the first element of an array is 0
a = [4,6,7,5] # simple array decleration
a.length # => 4
a.sort # => [4, 5, 6, 7]
a.sort.reverse # => [7, 6, 5, 4]
a[0] # => 4
a[3] # => 5
a[4] = 3 # => 3 ;resulting array is [4, 6, 7, 5, 3]
a[10] = 0 # => 0 ;resulting array is [4, 6, 7, 5, 3, nil, nil, nil, nil, nil, 0]
a.length # => 11
array of ranges are allowed to declare, Object Oriented!
HEX = [(0..9),('A'..'F')]
HEX.each { |x| x.each { |y| print y }} # outputs, 0123456789ABCDEF
Hashes
editHash is an associative array which is a collections of Keys and it's associated Values
capitals = {
:karnataka => 'Banglore'
:maharastra => 'Mumbai'
}
capitals[:westbengal] = 'Kolkata' # append a new element
capitals[:karnataka] = 'Bengaluru' # change an element's association
print '%d%' % 1 # is valid, => 1%
print '%d% ' % 1 # is invalid
Ruby 1.9.2 Version is used for the examples on Win Intel x86 / Linux AMD64 Platforms