ruby 字符串比较 .match vs .eql?

标签 ruby

当我使用 .match 和 .eql 时?对于字符串比较,他们给出了不同的结果

text_from_page = "wrong length (should be 64 characters)"
error_text = "wrong length (should be 64 characters)" 
if(text_from_page.eql? error_text)
 puts 'matched' 
else
  puts 'Not matched'
end

以下比较无效

if(text_from_page.match error_text)
 puts 'matched' 
else
  puts 'Not matched'
end

有人知道这是什么原因吗?

最佳答案

一如既往,不要只使用方法而不阅读它们的文档。可以有重要的注释。

这是 eql? :

Two strings are equal if they have the same length and content.

这是 match :

Converts pattern to a Regexp (if it isn’t already one), then invokes its match method on str. If the second parameter is present, it specifies the position in the string to begin the search.

注意关于转换的部分。在正则表达式中,() 等字符具有重要意义。你不能在这里随意使用match。它具有非常特殊的功能。

你很少看到 .eql? 在实际的 Ruby 代码中使用,约定很简单:

text_from_page == error_text

eql? 方法主要供内部使用。它在进行比较以及在数组或哈希等容器中查找内容时发挥作用。

关于ruby 字符串比较 .match vs .eql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42517102/

相关文章:

php - 是否有在 LAMP 堆栈上运行的 DotNetOpenAuth 等效项?

ruby - 有没有办法在类中声明本地方法,ruby?

ruby-on-rails - Rails 中的时间数据类型

ruby-on-rails - 未初始化的常量 Active Scaffold Rails 2.3.5

ruby - Rails first_or_initialize 不更新记录

Javascript - "history.pushState"将常规 "&"替换为 "&"。如何避免?

ruby - 在 Qt::TreeWidget 中插入项目

ruby - ruby/ruby on rails 的 cometd 服务器选项?

ruby-on-rails - 将 RabbitMQ 与 Ruby 和 Node.js 应用程序一起使用?

ruby-on-rails - 除非另一个字段是真实的,否则如何测试验证存在?