Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Ruby each_with_index offset
- some_array.each_with_index{|item, index = 1| some_func(item, index) }
- [:foo, :bar, :baz].to_enum.with_index(1).each do |elem, i|
- puts "#{i}: #{elem}"
- end
- 1: foo
- 2: bar
- 3: baz
- some_array.each_with_index{|item, index| some_func(item, index+1)}
- some_array.each_with_index{|item, i| j = i + 1; some_func(item, j)}
- module Enumerable
- def each_with_index_from_one *args, &pr
- each_with_index(*args){|obj, i| pr.call(obj, i+1)}
- end
- end
- %w(one two three).each_with_index_from_one{|w, i| puts "#{i}. #{w}"}
- # =>
- 1. one
- 2. two
- 3. three
- offset = 2
- some_array[offset..-1].each_with_index{|item, index| some_func(item, index+offset) }
- some_array[offset..-1].each_with_index{|item, index| some_func(item, index) }
- some_array[offset..-1].each_with_index{|item, index| some_func(item, index+offset) }
- some_array[offset..-1].each_with_index{|item, index| index+=offset; some_func(item, index) }
- some_array[1000,-1] => nil
- nil.each_with_index => Error 'undefined method `each_with_index' for nil:NilClass'
- (some_array[offset..-1]||[]).each_with_index{|item, index| some_func(item, index) }
- offset = 1000
- some_array[offset..-1].each_with_index{|item, index| some_func(item, index) } if offset <= some_array.size
Advertisement
Add Comment
Please, Sign In to add comment