Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discriminate 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? Certainly I can use a loop variable i and keep track if i==0 or [email protected] but isn't that too dumb?

like image 733
OneZero Avatar asked Jun 16 '13 15:06

OneZero


2 Answers

One of the nicer approaches is:

@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
like image 192
Boris Stitnicky Avatar answered Nov 07 '22 14:11

Boris Stitnicky


You can use each_with_index and then use the index to identify the first and last items. 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

Alternately, if you prefer you could separate the 'middle' of the array like so:

# 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)

With both these methods you have to be careful about the desired behaviour when there are only one or two items in the list.

like image 6
thomasfedb Avatar answered Nov 07 '22 14:11

thomasfedb