Distinguish the first and last element in each?

@example.each do |e| #do something here end 

Here I want to do something different with the first and last element in each, how should I achieve this? Of course, I can use the loop variable i and track if i==0 or i==@example.size , but is it too stupid?

+8
ruby ruby-on-rails
source share
3 answers

One of the best approaches:

 @example.tap do |head, *body, tail| head.do_head_specific_task! tail.do_tail_specific_task! body.each { |segment| segment.do_body_segment_specific_task! } end 
+24
source share

You can use each_with_index and then use an index to identify the first and last elements. For example:

 @data.each_with_index do |item, index| if index == 0 # this is the first item elsif index == @data.size - 1 # this is the last item else # all other items end end 

Alternatively, if you prefer, you can separate the "middle" array as follows:

 # This is the first item do_something(@data.first) @data[1..-2].each do |item| # These are the middle items do_something_else(item) end # This is the last item do_something(@data.last) 

In both of these methods, you must be careful with the desired behavior if there is only one or two elements in the list.

+5
source share

A fairly general approach is as follows (when there are no duplicates in the array).

 @example.each do |e| if e == @example.first # Things elsif e == @example.last # Stuff end end 

If you suspect that the array may contain duplicates (or if you prefer this method), then take the first and last elements from the array and process them outside the block. When using this method, you must also extract the code that is valid for each instance so that the function does not repeat:

 first = @example.shift last = @example.pop # @example no longer contains those two items first.do_the_function @example.each do |e| e.do_the_function end last.do_the_function def do_the_function(item) act on item end 
+2
source share

All Articles