1

For backward compatibility reasons I want to implement the String#codepoints ruby method (introduced in 1.9.1).

I am thinking

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

but I am concerned that #ord will not work properly with earlier versions of ruby.

mrzasa
  • 22,895
  • 11
  • 56
  • 94
Obromios
  • 15,408
  • 15
  • 72
  • 127
  • 1
    Install the [backports](https://github.com/marcandre/backports) gem and `require backports/1.9.1/string/codepoints`. It uses `unpack('U*')` under the hood, you can find the source code [here](https://github.com/marcandre/backports/blob/master/lib/backports/1.9.1/string/codepoints.rb). – Stefan Feb 12 '19 at 08:58

1 Answers1

1

ord was introduced in Ruby 1.9.1, see APIDock.

For ASCII strings you can use #bytes, for Unicode it won't behave in the same way as #codepoints.

In Ruby 1.8.x you can use ? to get char numeric value, I don't know what to use for 1.9.0.

Btw rubies older than 2.3 are not supported any more, consider upgrading.

mrzasa
  • 22,895
  • 11
  • 56
  • 94
  • It is not my choice, I am trying pass the CI tests for a pull request on a gem, and passing ruby 1.8.7 is one of the tests. – Obromios Feb 12 '19 at 08:31
  • I can't install 1.8.7 to test it, but you can try `string.bytes.map{|b| ?b}` – mrzasa Feb 12 '19 at 08:35
  • Btw I'd consider contacting the gem maintainer and convince them to drop 1.8.7 support – mrzasa Feb 12 '19 at 08:36
  • They are planning to drop it in the next major release, I doubt very much they will do so before then, I expect they have heard that argument many times before. When I put ```str.bytes.map { |b| ?b }``` I get a rubycop error to the effect that ```Do not use the character literal - using string literal instead.```. I need to pass all rubocop tests as well, so is there a way of expressing this that will not trigger a rubocop error? – Obromios Feb 12 '19 at 09:34
  • `# rubocop:disable RuleByName` https://stackoverflow.com/questions/26342570/rubocop-linelength-how-to-ignore-lines-with-comments – mrzasa Feb 12 '19 at 09:47
  • Thank you, I try this and see their response is. When finished I may come back and tidy this up. – Obromios Feb 12 '19 at 09:50
  • @mrzasa: `?b` is equal to `'b'` on Ruby 1.9+ and equal to `97` on Ruby pre-1.9. How is replacing the entire string with 97s going to solve the problem? E.g. `'Hello'.bytes.map {|b| ?b }` is `['b', 'b', 'b', 'b', 'b']` on Ruby 1.9+ and `[97, 97, 97, 97, 97]` on Ruby 1.8. – Jörg W Mittag Feb 12 '19 at 13:20