I want to skip iteration for few values depending on dynamic condition.
Say I have a persons array [1,2,3,4,5,6,7,8] and while iterating if the
one of the values equals 2, then it should skip iteration for the next
two values (in this case it is 3 and 4)
In this case the output should be: [1,2,5,6,7,8]
persons = [1,2,3,4,5,6,7,8]
persons.each do |x|
if x == 2
# the next x value should be 5 in my case
end
p x
end
I want to skip iteration for few values depending on dynamic condition.
Say I have a persons array [1,2,3,4,5,6,7,8] and while iterating if the
one of the values equals 2, then it should skip iteration for the next
two values (in this case it is 3 and 4)
In this case the output should be: [1,2,5,6,7,8]
persons = [1,2,3,4,5,6,7,8]
persons.each do |x|
if x == 2
# the next x value should be 5 in my case
end
p x
end
How can I do it in Ruby ?
Okay! So do you want the original array intact or output to hold in a
different array?
On Fri, Feb 15, 2013 at 4:11 PM, Saurav Chakraborty <lists@ruby-forum.com>wrote:
I want to skip iteration for few values depending on dynamic condition.
Say I have a persons array [1,2,3,4,5,6,7,8] and while iterating if the
one of the values equals 2, then it should skip iteration for the next
two values (in this case it is 3 and 4)
Can you explain the dynamic condition? Your example has been solved by a number of people for an equality test, but do you require something more complicated? #reject will probably get you most of the way there, but there may be other ways of approaching the problem if 'dynamic' is something involving expensive operations, possible exceptions (integer overflow–if 2**x> 100–could be a problem), etc.
-a.
···
On 15 Feb 2013, at 3:11 AM, Saurav Chakraborty <lists@ruby-forum.com> wrote:
I want to skip iteration for few values depending on dynamic condition.
Say I have a persons array [1,2,3,4,5,6,7,8] and while iterating if the
one of the values equals 2, then it should skip iteration for the next
two values (in this case it is 3 and 4)
In this case the output should be: [1,2,5,6,7,8]
persons = [1,2,3,4,5,6,7,8]
persons.each do |x|
if x == 2
# the next x value should be 5 in my case
end
p x
end
irb(main):011:0> show = -1
=> -1
irb(main):012:0> persons.each_with_index {|x, i| show = i + 2 if x ==
2; puts x if i > show}
1
5
6
7
8
=> [1, 2, 3, 4, 5, 6, 7, 8]
or
irb(main):013:0> persons.inject(0) {|miss, x| if x == 2 then 2 else
puts x if miss <= 0; miss - 1 end}
1
5
6
7
8
=> -4
Kind regards
robert
···
On Fri, Feb 15, 2013 at 1:17 PM, botp <botpena@gmail.com> wrote:
On Fri, Feb 15, 2013 at 4:11 PM, Saurav Chakraborty <lists@ruby-forum.com> > wrote:
I want to skip iteration for few values depending on dynamic condition.
Say I have a persons array [1,2,3,4,5,6,7,8] and while iterating if the
one of the values equals 2, then it should skip iteration for the next
two values (in this case it is 3 and 4)