Tomas.R
Tomas.R

Reputation: 953

Deleting a key-value pair from hash (RUBY)

movies = {
  StarWars: 4.8, 
  Divergent: 4.7
  }

print movies

This code returns a hash:

{:StarWars=>4.8, :Divergent=>4.7}

When I try to delete a key-value pair and print movies again:

movies = {
  StarWars: 4.8, 
  Divergent: 4.7
  }


movies = movies.delete("Divergent".to_sym)
print movies

 

I get :

4.7

How do I delete a key-value pair, so that after I ask to print the contents of movies hash I get :

{:StarWars=>4.8}

Upvotes: 0

Views: 2823

Answers (1)

eux
eux

Reputation: 3282

Hash#delete returns the value of provided key, movies.delete("Divergent".to_sym) returns 4.7, and you reassign it to movies, now movies is 4.7.

So you could just delete and don't reassign:

movies.delete("Divergent".to_sym)
print movies # => {:StarWars=>4.8}

Upvotes: 7

Related Questions