Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings that compare equal don't find same objects in Hash

I have two strings that appear equal:

context = "Marriott International World’s Most ADMIRED Lodging Company by FORTUNE for 14th yr. via @FortuneMagazine http://cnnmon.ie/1kcFZSQ"
slice_str = context.slice(105,24) # => "http://cnnmon.ie/1kcFZSQ"
str = "http://cnnmon.ie/1kcFZSQ"

slice_str == str                  # => true
slice_str.eql? str                # => true

But when I look up values in a hash where the keys are the strings, they do not return the same thing in Ruby 2.1.0 and Ruby 2.1.1:

redirects = {"http://cnnmon.ie/1kcFZSQ"=>""}
redirects.key?(slice_str)         # => false
redirects.key?(str)               # => true

What explanation is there for this behaviour? Ruby 1.9.3 works as expected.

like image 813
Rich Sutton Avatar asked May 30 '14 02:05

Rich Sutton


1 Answers

This was a bug in ruby < 2.1.3

$ rvm use 2.1.2
Using /Users/richniles/.rvm/gems/ruby-2.1.2
$ irb
2.1.2 :001 > context = "Marriott International World’s Most ADMIRED Lodging Company by FORTUNE for 14th yr. via @FortuneMagazine http://cnnmon.ie/1kcFZSQ"
 => "Marriott International World’s Most ADMIRED Lodging Company by FORTUNE for 14th yr. via @FortuneMagazine http://cnnmon.ie/1kcFZSQ" 
2.1.2 :002 > slice_str = context.slice(105,24) # => "http://cnnmon.ie/1kcFZSQ"
 => "http://cnnmon.ie/1kcFZSQ" 
2.1.2 :003 > str = "http://cnnmon.ie/1kcFZSQ"
 => "http://cnnmon.ie/1kcFZSQ" 
2.1.2 :004 > redirects = {"http://cnnmon.ie/1kcFZSQ"=>""}
 => {"http://cnnmon.ie/1kcFZSQ"=>""} 
2.1.2 :005 > redirects.key?(slice_str) 
 => false 
2.1.2 :006 > redirects.key?(str)  
 => true 

but do the same in ruby 2.1.3:

 $ rvm use 2.1.3
 Using /Users/richniles/.rvm/gems/ruby-2.1.3
 $ irb
 2.1.3 :001 > context = "Marriott International World’s Most ADMIRED Lodging Company by FORTUNE for 14th yr. via @FortuneMagazine http://cnnmon.ie/1kcFZSQ"
  => "Marriott International World’s Most ADMIRED Lodging Company by FORTUNE for 14th yr. via @FortuneMagazine http://cnnmon.ie/1kcFZSQ" 
 2.1.3 :002 > slice_str = context.slice(105,24) # => "http://cnnmon.ie/1kcFZSQ"
  => "http://cnnmon.ie/1kcFZSQ" 
 2.1.3 :003 > str = "http://cnnmon.ie/1kcFZSQ"
  => "http://cnnmon.ie/1kcFZSQ" 
 2.1.3 :004 > redirects = {"http://cnnmon.ie/1kcFZSQ"=>""}
  => {"http://cnnmon.ie/1kcFZSQ"=>""} 
 2.1.3 :005 > redirects.key?(slice_str) 
  => true 
 2.1.3 :006 > redirects.key?(str)  
  => true 
like image 123
Rich Niles Avatar answered Jan 01 '23 21:01

Rich Niles