For this example hash
hash = {:key=>"value"}
all of these are true
:
hash.key?(:key)
hash.has_key?(:key) #deprecated in favor of .key?
hash.include?(:key)
hash.member?(:key)
Ruby Docs offer the same explanation for all three
"Returns `true` if the given key is present in ..."
My question is: in real-world Ruby usage, are there specific use cases for each of these? Or, is this simply a matter of having multiple ways to solve the same problem?
Links to specific documentation or references are greatly appreciated!
If you open up Ruby doc on Hashes, then find your methods and open a their source code you can see that have the same source code.
So to answer a question in proper manner: I would dare to call them aliases (same but differently called/named), but I find them useful to improve the readability of my code.
Many clases in Ruby have multiple methods that do exactly the same thing. This is to accommodate people that are used to a particular convention because of exposure to or familiarity with another programming language. Common examples:
"string".length == "string".size
%w[ x ].length == %w[ x ].size
%w[ a b c ].map(&:uppercase) == %w[ a b c ].collect(&:uppercase)
Most of the time the documentation will provide some hint that this is simply an alternate name for another method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With