In Ruby step
method iterates evaluation of the given block, which takes a date object. The limit should be a date object. For example,
1 2 3 4 5 6 7 | # import date library require 'date' # on 2012,1,1 the day was Sunday x = Date.new(2012).step(Date.new(2012,1,1)).select{|d| d.monday?}.size # on 2012,1,2 first monday of that year x = Date.new(2012).step(Date.new(2012,1,2)).select{|d| d.monday?}.size puts x |
Output:
0
1
NOTE: From the above example, it is easy to understand that .step
method iterates until it find the required day which is also indicated in the code. This code tells that, this is the first monday of that particular year.
Syntax of step
Method in Ruby
Date.new(x).step
Parameter of step
Method in Ruby
x
– where x
is any valid date object. This parameter is required.Error Handling of step
Method in Ruby
If the
x
parameter is not a valid date object the step
method will return an error and it could be due to the wrong format of the date in a code, the use of zero or the missing of any other character.Return Value of step
Method in Ruby
The
step
method will return the number of the special day indicated in the code from the whole year like this is the 2nd, 10th or 15th monday of that year.Ruby step
Method Example
1 2 3 4 | # import date library require 'date' x = Date.new(2012).step(Date.new(2012,1,23)).select{|d| d.monday?}.size puts x |
Output:
4
Ruby Different Methods of step
1 2 3 4 | # import date library require 'date' x = Date.new(2012).step(Date.new(2012,2,20)).select{|d| d.monday?}.size puts x |
Output:
8
Use of Step Method in Ruby with Example
1 2 3 4 5 6 | # import date library require 'date' # you can get desired year x = Date.new(2012).step(Date.new(2012,3,12)).select{|d| d.monday?}.size x = Date.new(2012).step(Date.new(2012,4,16)).select{|d| d.monday?}.size puts x |
Output:
11
16
Loading...