i looked at an example
rng.each {| i | block } -> rng
Iterates over the elements rng, passing each in turn to the block.
(10…15).each do |n|
print n, ’ ’
end
produces: 10 11 12 13 14 15
when i try the same, it does not work. here is my attempt.
irb(main):025:0> (15…10).each do |n|
irb(main):026:1* print n
irb(main):027:1> end
=> 15…10
irb(main):028:0> (5…10).each do |n|
irb(main):029:1* print n
irb(main):030:1> end
5678910=> 5…10
irb(main):031:0>
so i cannot have a range that is decreasing in numbers. for eg
1…5 can be 1,2,3,4,5
how can i do 5…1 ie 5,4,3,2,1
Range is by definition increasing. If you want to iterate over numbers
from 5 to 1, you can do it like this: (1…5).to_a.reverse.each or better
(1…5).to_a.reverse_each (this does not allocate the reversed array,
just iterates in the opposite order). Both these methods allocate the
array of all the values, though, so if your range is big, you should
probably use an explicit loop with a decremented value and a stop
condition.
Past-endpoint ranges (7…3) seemed too ambiguous, so I just disallowed
it. In particular if (3…5).to_a == [3, 4], then
reversible(5…3).to_a == [4, 3]. Do not want.
I considered using the name ‘magnetic’ instead of ‘reversible’, as it
has the effect of flipping around to find the right polarity.
I used this as a self-tutorial for learning RSpec for the first time.
% spec ./specification.rb -fs
Synopsis
(3…7).to_a #=> [3, 4, 5, 6, 7]
(7…3).to_a #=> []
reversible(3…7).to_a #=> [3, 4, 5, 6, 7]
reversible(7…3).to_a #=> [7, 6, 5, 4, 3]
[…]
I received an email which indicated this needs some explanation. Yes,
this is the RSpec output. I give it an equation, run it through RSpec,
then transform it as above. So in this case the test and the
documentation are the same thing.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.