Last active
August 29, 2015 13:56
-
-
Save boddhisattva/9086718 to your computer and use it in GitHub Desktop.
Iterators in Ruby
This file contains hidden or 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 hidden or 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment