1

I am trying to remove the entire row for id and name for 001 and 002from the sample:

sample = [{"id"=>"000", "name"=>"Bob"},
     {"id"=>"001", "name"=>"Sally"},
     {"id"=>"002", "name"=>"Spike"},
     {"id"=>"003", "name"=>"Junior"},
     {"id"=>"004", "name"=>"Tater"}]

remove_ele = ["001","002"]

I have tried the following, but it doesn't seem to work:

sample.delete_if { |key, value| sample[x]["id"] == remove_ele[x] }

essentially, i'm trying to compare the 2 and any matches in remove_ele it will just delete the entire row/element in sample.

Please assist in best way to do this in ruby.

2 Answers 2

5

there are a few problems with this block you've provided to delete_if:

sample.delete_if { |key, value| sample[x]["id"] == remove_ele[x] }

Since sample is an array of hashes, using the delete_if iterator will pass a hash to the block. I.e. it should be |hash| instead of |key, value|.

Secondly, x will not be defined in your block.

A functional solution would be this:

remove_ele.each do |id_to_remove|
  sample.delete_if { |hash| hash['id'] == id_to_remove }
end

Alternatively, which does the same thing:

sample.delete_if { |hash| remove_ele.include? hash['id'] }
Sign up to request clarification or add additional context in comments.

1 Comment

Upvotted because you provided explanation with your code!
2

sample.delete_if {|x| remove_ele.include? x['id'] }

1 Comment

Down voted due to lack of explanation. Providing the code without explanations does nothing for the op

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.