Deleting a hash from array of hashes in Ruby
Use Array#delete_if
:
arr = [{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}, {"k1"=>"v3", "k2"=>"5.1%"}]
arr.delete_if { |h| h["k1"] == "v3" }
#=> [{"k1"=>"v1", "k2"=>"75.1%"}, {"k1"=>"v2", "k2"=>"-NA-"}]
If there is no hash matching the condition, the array is left unchanged.
Remove Hash from array based on key in Ruby
Elements of the array are hashes, so you need to treat them as hashes:
@array.delete_if{|h| h[:total_duration] == 0}
# => [{:tid=>"m121459", :uid=>"S2G1", :total_duration=>713}]
@array
#=> [{:tid=>"m121459", :uid=>"S2G1", :total_duration=>713}]
Remove key/value pair from array of hashes
Try the following code:
a = [
{'id'=>'1','imageUrl'=>'abc','name'=>'x'},
{'id'=>'2','imageUrl'=>'efg','name'=>'y'},
{'id'=>'3','imageUrl'=>'hij','name'=>'z'}
]
a.each { |h| h.delete("name") }
p a # => [{"id"=>"1", "imageUrl"=>"abc"}, {"id"=>"2", "imageUrl"=>"efg"}, {"id"=>"3", "imageUrl"=>"hij"}]
Delete item from Ruby array of hashes if item matches array of strings
It looks like your hash_list
is missing some closing brackets. I've added them below. Try running this in irb:
playlist_track_names = ["I Might", "Me & You", "Day 1", "I Got You (feat. Nana Rogues)", "Feels So Good (feat. Anna of the North)", "306", "Location Unknown (feat. Georgia)", "Crying Over You (feat. BEKA)", "Shrink", "I Just Wanna Go Back", "Sometimes", "Forget Me Not"]
hash_list = [
{"id"=>"1426036284", "type"=>"songs", "attributes"=>{"name"=>"I Might", "albumName"=>"Love Me / Love Me Not" } },
{"id"=>"1426036285", "type"=>"songs", "attributes"=>{"name"=>"Feels So Good (feat. Anna of the North)", "albumName"=>"Love Me / Love Me Not" } },
{"id"=>"1426036286", "type"=>"songs", "attributes"=>{"name"=>"Forget Me Not", "albumName"=>"Love Me / Love Me Not" } },
{"id"=>"1426036287", "type"=>"songs", "attributes"=>{"name"=>"Some Other Name", "albumName"=>"Love Me / Love Me Not" } }
]
hash_list.delete_if { |i| playlist_track_names.include? i["attributes"]["name"] }
puts hash_list
How to delete an array inside a hash
You can use transform_values
and select the second element from the array in positions
:
my_hash = {"positions"=>[[2, 3, 13, 56], [2, 3, 13]]}
wanted_hash = my_hash.transform_values { |value| value[1] }
# {"positions"=>[2, 3, 13]}
Notice it doesn't modify my_hash
, it returns a new object.
Filter values from an array of hashes and delete them from the original array
Use partition
to separate the input array into 2 arrays based on the filtering condition. You can modify the input array in place too, by using it on the left-hand side of the assignment:
my_array = [{ id: 1, val: 'foo' } , { id: 2, val: 'bar' } , { id: 3, val: 'baz' }]
# split input array into 2 new arrays, keep input array as is:
selected, other = my_array.partition { |hash| hash[:id] == 1 }
puts "#{selected}" # [{:id=>1, :val=>"foo"}]
puts "#{other}" # [{:id=>2, :val=>"bar"}, {:id=>3, :val=>"baz"}]
# remove from the input array selected elements into 1 new array,
# keep the rest in the input array (change the input array in-place):
selected, my_array = my_array.partition { |hash| hash[:id] == 1 }
puts "#{selected}" # [{:id=>1, :val=>"foo"}]
puts "#{my_array}" # [{:id=>2, :val=>"bar"}, {:id=>3, :val=>"baz"}]
Note that partition
can be thought of as both select
and reject
(or filter
and reject
) in a single operation. Here is a simple example to illustrate what partition
does:
x, y = [3, 2, 1, 4].partition { |n| n < 3 }
puts "#{x}; #{y}" # [2, 1]; [3, 4]
Remove an item from each hash in an Array of hashes
You can use map and delete
this will work the actual instances of the hashes, so the array will be modified.
array.each{ |hash| hash.delete('cat') }
you can do this to get a new array and keep the first one non touched.
new_array = array.map do |hash|
new_hash = hash.dup
new_hash.delete('cat')
new_hash
}
Deleting a specific hash inside an array of hashes using a variable
Try this:
arr.delete_if { |hash| id.include?(hash[:id]) }
Note (comparison to the #reject
suggestion): #delete_if
returns the unchanged array if there is nothing to delete. #reject
returns nil
. Also, #delete_if
modifies the array in place, whereas #reject
(without !
) simply returns a changed version of the array but leaves the original unchanged.
edit
Note: the use of include?
here assumes that there may be multiple integers that are being filtered out, i.e. if id
(or ids
) is actually an array. If you just need to filter one ID, you can use a straightforward comparison with hash[:id] == id
inside the block. Thanks to smathy for pointing this out in the comments.
Related Topics
Simple Ruby Input Validation Library
What Does the Operator ||= Stand for in Ruby
Ruby on Rails: Yielding Specific Views in a Specific Places in the Layout
How to Force One Field in Ruby's CSV Output to Be Wrapped with Double-Quotes
How to Setup Urls for Static Site with Ruby Rack on Heroku
Most Efficient Way to Calculate Hamming Distance in Ruby
Using Ruby and Net-Ssh, How to Authenticate Using the Key_Data Parameter with Net::Ssh.Start
Rails: Pg::Insufficientprivilege: Error: Permission Denied for Relation Schema_Migrations
Convert Ruby to Low Level Languages
Single Table Inheritance or Class Table Inheritance
Sinatra Static Assets Are Not Found When Using Rackup
How to Reference a Lambda from Within Itself Using Ruby
Rails 3, Check CSV File Encoding Before Import
How to Convert a JSON String to an Object
Using Ruby, Reading a File, Containing Name/Value Pairs into a Hash
Convert Array to Hash While Preserving Array Index Values in Ruby