From 068651582ace89d781532571794ef4e00f6133c0 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 21 May 2016 15:13:24 -0500 Subject: [PATCH] Add Up And Down With Integers as a ruby til --- README.md | 1 + ruby/up-and-down-with-integers.md | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 ruby/up-and-down-with-integers.md diff --git a/README.md b/README.md index 7cccf0f..42b18b8 100644 --- a/README.md +++ b/README.md @@ -333,6 +333,7 @@ _422 TILs and counting..._ - [Summing Collections](ruby/summing-collections.md) - [Uncaught Exceptions In Pry](ruby/uncaught-exceptions-in-pry.md) - [`undef_method` And The Inheritance Hierarchy](ruby/undef-method-and-the-inheritance-hierarchy.md) +- [Up And Down With Integers](ruby/up-and-down-with-integers.md) - [Who Are My Ancestors?](ruby/who-are-my-ancestors.md) - [Zero Padding](ruby/zero-padding.md) diff --git a/ruby/up-and-down-with-integers.md b/ruby/up-and-down-with-integers.md new file mode 100644 index 0000000..abeff9b --- /dev/null +++ b/ruby/up-and-down-with-integers.md @@ -0,0 +1,31 @@ +# Up And Down With Integers + +Ruby's [`Integer`](http://ruby-doc.org/core-2.2.0/Integer.html) class comes +with an `#upto` and a `#downto` method. Both of these methods can be used to +iterate from one number up or down to, respectively, another number. + +Let's count to 3 + +```ruby +> 1.upto(3) { |x| puts x } +1 +2 +3 +``` + +This of course can easily and perhaps more idiomatically be accomplished +with a range and the `#each` method (e.g. `(1..3).each { |x| puts x }`. + +We cannot, however, simulate the `#downto` method with a range (at least, +not very cleanly). So, if you need to count down to something, this is going +to be the cleanest and clearest way. + +```ruby +> 5.downto(2) { |x| puts x } +5 +4 +3 +2 +``` + +The return value for both methods is always the integer we started with.