Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 22nd, 2012  |  syntax: None  |  size: 1.25 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Ruby each_with_index offset
  2. some_array.each_with_index{|item, index = 1| some_func(item, index) }
  3.        
  4. [:foo, :bar, :baz].to_enum.with_index(1).each do |elem, i|
  5.   puts "#{i}: #{elem}"
  6. end
  7.        
  8. 1: foo
  9. 2: bar
  10. 3: baz
  11.        
  12. some_array.each_with_index{|item, index| some_func(item, index+1)}
  13.        
  14. some_array.each_with_index{|item, i| j = i + 1; some_func(item, j)}
  15.        
  16. module Enumerable
  17.   def each_with_index_from_one *args, &pr
  18.     each_with_index(*args){|obj, i| pr.call(obj, i+1)}
  19.   end
  20. end
  21.  
  22. %w(one two three).each_with_index_from_one{|w, i| puts "#{i}. #{w}"}
  23. # =>
  24. 1. one
  25. 2. two
  26. 3. three
  27.        
  28. offset = 2
  29. some_array[offset..-1].each_with_index{|item, index| some_func(item, index+offset) }
  30.        
  31. some_array[offset..-1].each_with_index{|item, index| some_func(item, index) }
  32. some_array[offset..-1].each_with_index{|item, index| some_func(item, index+offset) }
  33. some_array[offset..-1].each_with_index{|item, index| index+=offset; some_func(item, index) }
  34.        
  35. some_array[1000,-1] => nil
  36. nil.each_with_index => Error 'undefined method `each_with_index' for nil:NilClass'
  37.        
  38. (some_array[offset..-1]||[]).each_with_index{|item, index| some_func(item, index) }
  39.        
  40. offset = 1000
  41.  some_array[offset..-1].each_with_index{|item, index| some_func(item, index) } if offset <= some_array.size