Ruby 3.1 中数组索引的奇怪行为
Weird behaviour of Array index in Ruby 3.1
我不知道为什么我的 ruby 会出现这种情况,但你看到同样的行为了吗?
3.1.2 :001 > ["url", "label:from", "label:type", "label:batch", "note"].index('url')
=> nil
3.1.2 :002 > ["url", "label:from", "label:type", "label:batch", "note"].index('note')
=> 4
3.1.2 :003 > ["Url", "label:from", "label:type", "label:batch", "note"].index('Url')
=> 0
小写时找不到'url'。这是保留字吗?
编辑:似乎无法找到第一次出现的“url”字符串:
["note", "url", "label:from", "label:type", "label:batch", "note", "url"].index 'url'
=> 6
数组中的第一个条目与您想象的不一样。查看原始字节,您会看到:
["url", "label:from", "label:type", "label:batch", "note"].first.bytes.map { |x| x.to_s(16) }
# ["ef", "bb", "bf", "75", "72", "6c"]
0x75 0x72 0x6c
是您看到的 "url"
,0xef 0xbb 0xbf
是 Byte Order Mark (BOM). Byte order is meaningless in UTF-8 so BOMs should not be used, they're valid but unusual and not recommended. You can have Ruby strip the BOMs while reading files,如果这是字符串的来源。
我不知道为什么我的 ruby 会出现这种情况,但你看到同样的行为了吗?
3.1.2 :001 > ["url", "label:from", "label:type", "label:batch", "note"].index('url')
=> nil
3.1.2 :002 > ["url", "label:from", "label:type", "label:batch", "note"].index('note')
=> 4
3.1.2 :003 > ["Url", "label:from", "label:type", "label:batch", "note"].index('Url')
=> 0
小写时找不到'url'。这是保留字吗?
编辑:似乎无法找到第一次出现的“url”字符串:
["note", "url", "label:from", "label:type", "label:batch", "note", "url"].index 'url'
=> 6
数组中的第一个条目与您想象的不一样。查看原始字节,您会看到:
["url", "label:from", "label:type", "label:batch", "note"].first.bytes.map { |x| x.to_s(16) }
# ["ef", "bb", "bf", "75", "72", "6c"]
0x75 0x72 0x6c
是您看到的 "url"
,0xef 0xbb 0xbf
是 Byte Order Mark (BOM). Byte order is meaningless in UTF-8 so BOMs should not be used, they're valid but unusual and not recommended. You can have Ruby strip the BOMs while reading files,如果这是字符串的来源。