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

前端 未结 10 878
自闭症患者
自闭症患者 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:24

    I'd like to +1 dylanfm and AShelly's comment but add the [0]:

    'A'.unpack('C')[0]

    The unpack call returns an Array containing a single integer, which is not always accepted where an integer is wanted:

    $ ruby -e 'printf("0x%02X\n", "A".unpack("C"))'
    -e:1:in `printf': can't convert Array into Integer (TypeError)
        from -e:1
    $ ruby -e 'printf("0x%02X\n", "A".unpack("C")[0])'
    0x41
    $ 
    

    I'm trying to write code that works on Ruby 1.8.1, 1.8.7 and 1.9.2.

    Edited to pass C to unpack in uppercase, because unpack("c") gives me -1 where ord() gives me 255 (despite running on a platform where C's char is signed).

    0 讨论(0)
  • 2020-12-23 13:25

    Additionally, if you have the char in a string and you want to decode it without a loop:

    puts 'Az'[0]
    => 65
    puts 'Az'[1]
    => 122
    
    0 讨论(0)
  • 2020-12-23 13:31

    How about

    puts ?A

    0 讨论(0)
  • 2020-12-23 13:36

    In Ruby up to and including the 1.8 series, the following will both produce 65 (for ASCII):

    puts ?A
    'A'[0]
    

    The behavior has changed in Ruby 1.9, both of the above will produce "A" instead. The correct way to do this in Ruby 1.9 is:

    'A'[0].ord
    

    Unfortunately, the ord method doesn't exist in Ruby 1.8.

    0 讨论(0)
  • 2020-12-23 13:37

    You can have these:

    65.chr.ord
    'a'.ord.chr
    
    0 讨论(0)
  • 2020-12-23 13:37

    If you don't mind pulling the values out of an array, you can use "A".bytes

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