1

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}]
2
  • Shouldn't the output be [{:tid=>"m121459", :uid=>"S2G1", :total_duration=>713}] Commented Nov 25, 2019 at 13:09
  • @AlokSwain yes. You're correct Commented Nov 25, 2019 at 13:14

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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.

1 Comment

To date appear to have four identical answers. The first two were given within seconds of each other, so I can't object to having both. Having more, such as yours, given 16 minutes after the first, serve no purpose. That is the reason for my downvote.
1
@array.delete_if{|x| x[:total_duration] == 0}

this will solve your problem

1 Comment

To date appear to have four identical answers. The first two were given within seconds of each other, so I can't object to having both. Having more, given minutes later, such as yours, serve no purpose. You may not have not noticed the others before posting but that is no matter. That is the reason for my downvote.

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.