根據檔案,我想讓我的無年約會課程很好玩Range#include?,它必須實作的是:<=>
class Count
include Comparable
attr_reader :value
def initialize(value)
@value = value
end
def <=>(other)
value <=> other.value
end
end
讓我們試試 Ruby 3.1.1:
(Count.new(1)..Count.new(5)).include? Count.new(3)
# => in `each': can't iterate from Count (TypeError)
我不明白它為什么要在這里迭代,each應該沒有必要弄清楚包含。
知道我在這里做錯了什么嗎?感謝您的提示!
uj5u.com熱心網友回復:
檔案不正確或(我懷疑)已過時。Range#cover?以您期望的方式作業[我的粗體強調]:
cover?(object)→true或false
true如果給定的引數在 范圍內,則回傳self,false否則。使用非范圍引數 object ,使用
<=and<進行評估。
的檔案Range#include?包含一個有點不祥的陳述[粗體強調我的]:
如果 begin 和 end 是數字,
include?表現得像cover?[…]
但是當不是 numeric 時,這兩種方法可能會有所不同:
('a'..'d').include?('cc') # => false ('a'..'d').cover?('cc') # => true
在這里您可以看到不同之處:Range#cover?計算結果為true因為'a' <= 'cc' && 'cc' <= 'd',而Range#include?計算結果為false因為('a'..'d').to_a == ['a', 'b', 'c', 'd'],因此('a'..'d').each.include?('cc')是錯誤的。
請注意,使用的介紹性示例Time仍然有效,因為Time在 spec 中是明確的特殊情況。
有一個 規范說兩者Range#include?和Range#cover?使用<=>,但它只用Integers 測驗,我們從上面不祥的檔案中知道Range#include?并且Range#cover?行為相同。
s有很多特殊情況Range,這不是第一次導致錯誤和/或非直覺行為:
- Ruby:盡管回應 Succ / Bug #18237
TimeRange#each仍無法從時間開始迭代,根據評論洗掉不必要的檢查/ https://github.com/ruby/spec/pull/852 / https://github.com/紅寶石/紅寶石/拉/4928 - https://bugs.ruby-lang.org/issues/18155
- https://bugs.ruby-lang.org/issues/18577
- https://bugs.ruby-lang.org/issues/18580
- https://github.com/ruby/dev-meeting-log/blob/master/DevMeeting-2022-02-17.md#bug-18580-rangeinclude-inconsistency-for-beginless-string-ranges-zverok
Personally, I am not a big fan of all this special-casing. I assume it is done for performance reasons, but the way to get better performance is not to add weird special cases to the language specification, it is to remove them which makes the language simpler and thus easier to optimize. Or, put another way: at any given point in time, a compiler writer can either spend the time implementing weird special cases or awesome optimizations, but not both. XRuby, Ruby.NET, MacRuby, MagLev, JRuby, IronRuby, TruffleRuby, Rubinius, Topaz, and friends have shown that the way to get high-performance Ruby is a powerful compiler, not weird hand-rolled special-cased C code.
I would file a bug, if only to get some clarification into the docs and specs.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/455215.html
下一篇:gsub的意外結果與行尾匹配:cat/etc/hosts|ruby-ne'列印$_.gsub(/$/,%q(xxx))'
