Last active
December 13, 2015 16:48
-
-
Save brookr/4942865 to your computer and use it in GitHub Desktop.
Various types of Ruby string equality comparisons
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| >> s1 = "a" | |
| => "a" | |
| >> s2 = "a" | |
| => "a" | |
| >> s3 = s1 | |
| => "a" | |
| >> puts "s1 & s2 #{s1 == s2 ? 'do' : 'do not'} have identical content" | |
| s1 & s2 do have identical content | |
| >> puts "s1 & s2 #{s1 === s2 ? 'do' : 'do not'} have identical content" | |
| s1 & s2 do have identical content | |
| >> puts "s1 & s2 #{s1.eql?(s2) ? 'do' : 'do not'} have identical content" | |
| s1 & s2 do have identical content | |
| >> puts "s1 & s2 #{s1.equal?(s2) ? 'are' : 'are not'} the same objects" | |
| s1 & s2 are not the same objects | |
| >> puts "s1 & s3 #{s1.equal?(s3) ? 'are' : 'are not'} the same objects" | |
| s1 & s3 are the same objects |
Author
Author
The tricky thing is, this will override how case statements are compared. I'd prefer to have the looser match in many cases, but extra care should be taken when adding this to an existing codebase. In that case, I'd define the method as String#equiv? or similar. Ideally, Ruby would let us define something like ==~, but that generates a syntax error. C'mon, Ruby!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Seems like
===is a good candidate for case-insensitive, white space-insensitive comparison…which then allows for: