从哈希中删除键值对 (RUBY)

Deleting a key-value pair from hash (RUBY)

movies = {
  StarWars: 4.8, 
  Divergent: 4.7
  }

print movies

这段代码returns一个散列:

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

当我尝试删除键值对并再次打印电影时:

movies = {
  StarWars: 4.8, 
  Divergent: 4.7
  }


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

 

我得到:

4.7

如何删除键值对,以便在我要求打印电影散列的内容后得到:

{:StarWars=>4.8}

Hash#delete returns 提供的键的值 movies.delete("Divergent".to_sym) returns 4.7,然后将其重新分配给 movies,现在 movies4.7.

所以你可以 delete 而不是重新分配:

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