appleLover
appleLover

Reputation: 15691

Remove Items From Ruby Hashes of Array

data = {'results' => [1, 1, 1, 1, 0, 0, 1, 1, 1, 0], 
        'weather' => ["bad", "bad", "bad", "good", "good", "good", "good", "good", "bad", "bad"]}

results has ten entries, and weather has ten entries, they are aligned and correspond to each other. how can i delete from the variable data two entries from weather, and the corresponding entry from results, where weather == "bad" ?

Upvotes: 0

Views: 101

Answers (2)

Yevgeniy Anfilofyev
Yevgeniy Anfilofyev

Reputation: 4847

If I understand it right, you should find first occurence of 'bad' in weather array, get an index of this occurence and delete elements in both arrays (and do it twice):

data = {'results' => [1, 1, 1, 1, 0, 0, 1, 1, 1, 0], 
        'weather' => ["bad", "bad", "bad", "good", "good", "good", "good", "good", "bad", "bad"]}

2.times do
  idx = data['weather'].index('bad')
  data['weather'].delete_at(idx)
  data['results'].delete_at(idx)
end

p data

Result:

{"results"=>[1, 1, 0, 0, 1, 1, 1, 0],
 "weather"=>["bad", "good", "good", "good", "good", "good", "bad", "bad"]}

Upvotes: 2

Kumar Akarsh
Kumar Akarsh

Reputation: 4980

The following works:

index_array = []
counter = 0
data['weather'].each_with_index do |a,i|
  if a=="bad" and counter !=2
    data['results'][i] = nil
    data['weather'][i] = nil
    counter = counter + 1
  end
end

data['results'] = data['results'].compact
data['weather'] = data['weather'].compact

Upvotes: 0

Related Questions