Using Iterators 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.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# working with iterators | |
3.times { puts "thank you!" } | |
puts("\n") | |
data = [1,2,3,4,5] | |
data.each {|x| puts x} # note how x although its not being declared or defined.. works for each element of the array data.. | |
puts("\n") | |
[1,2,3,4,5].map { |x| puts x*x } | |
# see the beauty of iterators in Ruby in terms of how the factorial is implemented... | |
print("Enter the number whose factorial you want to find out: ") | |
n = gets.to_i | |
$factorial = 1 | |
2.upto(n) { |x| $factorial *= x } | |
puts("Factorial of #{n} is:- #{$factorial} ") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
thank you! | |
thank you! | |
thank you! | |
1 | |
2 | |
3 | |
4 | |
5 | |
1 | |
4 | |
9 | |
16 | |
25 | |
Enter the number whose factorial you want to find out: 4 | |
Factorial of 4 is:- 24 |
No comments:
Post a Comment