Jay Soriano
Jay Soriano

Reputation: 33

Why a ( ) instead of [ ] when deleting hashes?

Complete programming beginner just trying to clarify something, I was creating keys for a hash and decided I wanted to delete one. Here were my guesses:

hash["key"].­delete
hash.dele­te["key"]

I eventually looked it up and I'm suppose to use ( ):

hash.dele­te("key")

Since I used a [ ] to create the hash, why wouldn't I use it to delete a key? Also, and why wouldn't hash("key").delete work?

Upvotes: 0

Views: 153

Answers (2)

christianblais
christianblais

Reputation: 2458

hash.delete() is a method, where hash[] is a sugar syntax (but still a method). You can use hash.store(key, value) if you prefer consistency.

hash[:key] = :value
hash.store(:key, :value)
hash.delete(:key)

Upvotes: 2

Andrew Marshall
Andrew Marshall

Reputation: 96934

[] is actually a method of Hash, and is treated specially in the language so the parameter goes between the []. It's equivalent to store, which uses standard method syntax.

Likewise, delete is also a method, which takes one argument. Doing hash.delete['foo'] is trying to call delete (with no arguments), and then call [] on whatever it returns. Doing hash['foo'].delete is calling delete on whatever is stored in hash['foo'].

Upvotes: 10

Related Questions