Reputation: 33
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.delete["key"]
I eventually looked it up and I'm suppose to use ( )
:
hash.delete("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
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
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