Tuesday, February 18, 2014

Enumerables in Ruby

Using Enumerables in Ruby - Source for the tutorial is Ruby Programming Language
by Yukihiro Matsumoto(creator of Ruby) and David Flanagan.

The blog below has a sample code with output. The sample code below with inline comments in a way summarizes the concept(refer blog title) covered as part of the book.

#Playing with Enumerable Objects
squares = [1,2,3].collect { |x| x*x }
print("Squares:")
puts(squares)
puts("\n")
#--------------------------------------------------------------------------------------------------------------------------------
print("Odd numbers upto range:\n")
odds = (1..25).select { |x| x%2 != 0 }
puts(odds)
puts("\n")
#--------------------------------------------------------------------------------------------------------------------------------
print("Even numbers upto range:\n")
evens = (1..25).reject { |x| x%2 != 0 }
puts(evens)
puts("\n")
view raw enumerables.rb hosted with ❤ by GitHub
Squares:1
4
9
Odd numbers upto range:
1
3
5
7
9
11
13
15
17
19
21
23
25
Even numbers upto range:
2
4
6
8
10
12
14
16
18
20
22
24


No comments:

Post a Comment