On 2013-May-23, at 05:24 , Ajit Teli wrote:

> Can anyone help me on how to skip index in ARRAY.each_with_index loop?
> 
> Please look at below case:
> 
> In a ARRAY.each_with_index loop, I would like increase the index by 10
> whenever a condition is met.
> 
> arr is array of numbers from 0 to 50
> arr.each_with_index do |x,i|
>  if i % 10 == 0
>    puts "#{x} at #{i}"
>    i = i+10  //index increased by 10
>  end
> end
> 
> The output should be:
> 10 at 10
> 30 at 30
> 50 at 50
> 
> Thanks
> Ajit

You need to think about what you really need to do, look at the options to use 
select or reject/delete_if, or take the time to understand what next does. Of 
course, you don't seem to have even tried to run your code since your output 
lacks "0 at 0".

-Rob

For example:

irb2.0.0> arr = (0..50).to_a
#2.0.0 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
irb2.0.0>   arr.each_with_index do |element,index|
?>              next unless index % 10 == 0
irb2.0.0>     puts "#{element} at #{index}"
irb2.0.0>   end
0 at 0
10 at 10
20 at 20
30 at 30
40 at 40
50 at 50
#2.0.0 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
irb2.0.0>   arr.each.with_index.select {|element,index| index % 10 == 0}.each 
do |element,index|
?>              puts "#{element} at #{index}"
irb2.0.0>   end
0 at 0
10 at 10
20 at 20
30 at 30
40 at 40
50 at 50
#2.0.0 => [[0, 0], [10, 10], [20, 20], [30, 30], [40, 40], [50, 50]]


-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/4FA0239B-28B5-4432-B4DC-E578C5C50BB5%40agileconsultingllc.com?hl=en-US.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to