Skip to content

Instantly share code, notes, and snippets.

@boddhisattva
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save boddhisattva/9086718 to your computer and use it in GitHub Desktop.

Select an option

Save boddhisattva/9086718 to your computer and use it in GitHub Desktop.
Iterators in Ruby
# 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} ")
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