代码之家  ›  专栏  ›  技术社区  ›  Obromios

如何为pre-Ruby1.9.1实现string.codepoints

  •  1
  • Obromios  · 技术社区  · 6 年前

    出于向后兼容性的原因,我希望实现 String#codepoints Ruby方法(介绍于 1.9.1 )

    我在想

    def codepoints(str)
        str.split('').map(&:ord)
    end
    

    但我担心的是 #ord 无法与早期版本的Ruby一起正常工作。

    1 回复  |  直到 6 年前
        1
  •  1
  •   mrzasa    6 年前

    ord 在Ruby1.9.1中引入,请参见 APIDock .

    对于ASCII字符串,可以使用 #bytes ,用于Unicode it won't behave in the same way as #codepoints .

    在Ruby1.8.x中,您可以使用 ? 为了得到char数值,我不知道1.9.0应该使用什么。

    不再支持2.3以上的btw rubies,请考虑升级。