Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between key?, include? and member? in Ruby?

Tags:

ruby

key

hash

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!

like image 600
zeitchef Avatar asked Dec 04 '16 17:12

zeitchef


2 Answers

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.

like image 91
Saša Zejnilović Avatar answered Oct 18 '22 11:10

Saša Zejnilović


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.

like image 42
tadman Avatar answered Oct 18 '22 13:10

tadman