Skip to content

Instantly share code, notes, and snippets.

@brookr
Last active December 13, 2015 16:48
Show Gist options
  • Select an option

  • Save brookr/4942865 to your computer and use it in GitHub Desktop.

Select an option

Save brookr/4942865 to your computer and use it in GitHub Desktop.
Various types of Ruby string equality comparisons
>> 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
@brookr

brookr commented Feb 13, 2013

Copy link
Copy Markdown
Author

Seems like === is a good candidate for case-insensitive, white space-insensitive comparison…

class String
  def ===(str)
    str.is_a?(String) && self.spaceless.casecmp(str.spaceless) == 0
  end

  def spaceless
    self.gsub(/\s/, "")
  end
end

which then allows for:

>> "   fo   \t  o  " === "  f o o"
=> true

@brookr

brookr commented Feb 13, 2013

Copy link
Copy Markdown
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