What's the opposite of chr() in Ruby?

前端 未结 10 879
自闭症患者
自闭症患者 2020-12-23 12:53

In many languages there\'s a pair of functions, chr() and ord(), which convert between numbers and character values. In some languages, ord()

相关标签:
10条回答
  • 2020-12-23 13:39

    Try:

    'A'.unpack('c')
    
    0 讨论(0)
  • 2020-12-23 13:42

    Just came across this while putting together a pure Ruby version of Stringprep via RFCs.

    Beware that chr fails outside [0,255], instead use 1.9.x - 2.1.x portable replacements:

    [22] pry(main)> "\u0221".ord.chr
    RangeError: 545 out of char range
    from (pry):2:in 'chr'
    [23] pry(main)> x = "\u0221".unpack('U')[0]
    => 545
    [24] pry(main)> [x].pack('U')
    => "ȡ"
    [25] pry(main)>
    
    0 讨论(0)
  • 2020-12-23 13:45

    If String#ord didn't exist in 1.9, it does in 2.0:

    "A".ord #=> 65
    
    0 讨论(0)
  • 2020-12-23 13:49

    I'm writing code for 1.8.6 and 1.9.3 and I couldn't get any of these solutions to work in both environments :(

    However, I came across another solution: http://smajnr.net/2009/12/ruby-1-8-nomethoderror-undefined-method-ord-for-string.html

    That didn't work for me either but I adapted it for my use:

    unless "".respond_to?(:ord)
      class Fixnum
        def ord
          return self
        end
      end
    end

    Having done that, then the following will work in both environments

    'A'[0].ord

    0 讨论(0)
提交回复
热议问题