Tutorial by Examples

Ruby has many types of enumerators but the first and most simple type of enumerator to start with is each. We will print out even or odd for each number between 1 and 10 to show how each works. Basically there are two ways to pass so called blocks. A block is a piece of code being passed which will...
Enumerable is the most popular module in Ruby. Its purpose is to provide you with iterable methods like map, select, reduce, etc. Classes that use Enumerable include Array, Hash, Range. To use it, you have to include Enumerable and implement each. class NaturalNumbers include Enumerable de...

Map

Returns the changed object, but the original object remains as it was. For example: arr = [1, 2, 3] arr.map { |i| i + 1 } # => [2, 3, 4] arr # => [1, 2, 3] map! changes the original object: arr = [1, 2, 3] arr.map! { |i| i + 1 } # => [2, 3, 4] arr # => [2, 3, 4] Note: you can...
Arrays You can iterate over nested arrays: [[1, 2], [3, 4]].each { |(a, b)| p "a: #{ a }", "b: #{ b }" } The following syntax is allowed too: [[1, 2], [3, 4]].each { |a, b| "a: #{ a }", "b: #{ b }" } Will produce: "a: 1" "b: 2" ...
This iterates from 4 to 13 (inclusive). for i in 4..13 puts "this is #{i}.th number" end We can also iterate over arrays using for names = ['Siva', 'Charan', 'Naresh', 'Manish'] for name in names puts name end
Sometimes you want to know the position (index) of the current element while iterating over an enumerator. For such purpose, Ruby provides the with_index method. It can be applied to all the enumerators. Basically, by adding with_index to an enumeration, you can enumerate that enumeration. Index is ...

Page 1 of 1