Remove a key from list of hashes Suppose my milestone is this:

milestones = [ {state: 'unavailable'}, {state: 'arrived'}, {state: 'completed'} ]


I want to remove all the unavailable state from the list of hashes except the last one. My function works pretty well but I need some help to re factor it even further, and will appreciate any comments you can give. Here my code:

def filter_milestones(milestones)
      track_unavailable = Set.new
      filtered_milestones = []
      total_length = milestones.length
      if total_length == 1
        filtered_milestones = milestones
      else
        milestones.each_with_index do |value, index|
          if value[:state] == 'unavailable' &amp;&amp; index != total_length - 1
            track_unavailable.add index
          end
        end
        milestones.each_with_index do |value, index|
          unless track_unavailable.include? index
            filtered_milestones &lt;&lt; value
          end
        end
      end
      filtered_milestones
    end


So if my input milestone is [ {state: 'unavailable'}, {state: 'arrived'}, {state: 'completed'} ] then the return will be [ {state: 'arrived'}, {state: 'completed'} ].
Your solution looks overly complex. If I understood it correctly, you want to filter out all unavailable states except if it's the last element. A more declarative and idiomatic Ruby approach would be:

filtered_milestones = milestones.reject.with_index do |milestone, idx| 
  is_last_milestone = (idx == milestones.size - 1)
  milestone[:state] == "unavailable" &amp;&amp; !is_last_milestone
end