G.Brown
G.Brown

Reputation: 389

Remove Hash from array based on key in Ruby

I'm new to Ruby. This is my array containing multiple hash. Now, I want to remove all Hash whose ':total_duration' is 0. This is what I've tried, but nothing is happening.

@array = 
[{:tid=>"p121709", :uid=>"S2G1", :total_duration=>0},
{:tid=>"p121710", :uid=>"S2G1", :total_duration=>0},
{:tid=>"m121459", :uid=>"S2G1", :total_duration=>713}]
@op_arr.delete_if { |key, total_duration| [key].include? 0 }

The output should be

@array = [{:tid=>"m121459", :uid=>"S2G1", :total_duration=>713}]

Upvotes: 1

Views: 969

Answers (4)

Safwan S M
Safwan S M

Reputation: 123

@array.delete_if{|x| x[:total_duration] == 0}

this will solve your problem

Upvotes: 1

Amol Mohite
Amol Mohite

Reputation: 642

Try this

@array = [
    {:tid=>"p121709", :uid=>"S2G1", :total_duration=>0},
    {:tid=>"p121710", :uid=>"S2G1", :total_duration=>0},
    {:tid=>"m121459", :uid=>"S2G1", :total_duration=>713}]

    @array.delete_if{|e| e[:total_duration]== 0}
    # => [{:tid=>"m121459", :uid=>"S2G1", :total_duration=>713}]

Hope this will help for you.

Upvotes: 1

Alok Swain
Alok Swain

Reputation: 6519

@array = [{:tid=>"p121709", :uid=>"S2G1", :total_duration=>0},
{:tid=>"p121710", :uid=>"S2G1", :total_duration=>0},
{:tid=>"m121459", :uid=>"S2G1", :total_duration=>713}]

@array.reject!{|e| e[:total_duration].zero?}

P.S - I think the output you need is [{:tid=>"m121459", :uid=>"S2G1", :total_duration=>713}] @array has one element which is a Hash and not what is posted in the question i.e. [{{:tid=>"m121459", :uid=>"S2G1", :total_duration=>713}}]

Upvotes: 4

mrzasa
mrzasa

Reputation: 23307

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}] 

Upvotes: 3

Related Questions