我有两个字符串看起来相等:
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
但是当我在一个哈希中查找值时,键是字符串,它们在Ruby 2.1.0和Ruby 2.1.1中不会返回相同的东西:
redirects = {"http://cnnmon.ie/1kcfZSQ"=>""} redirects.key?(slice_str) # => false redirects.key?(str) # => true
这个行为有什么解释? Ruby 1.9.3按预期工作.
解决方法
这是一个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
但是在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