gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:07:08 34 4
gpt4 key购买 nike

当我使用 .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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com