Newbie Q: Getting character codes

I need to get at the character code used to represent a character. I
realise that “f”[0] will return the code for “f” (102), but I read in
a FAQ that this behaviour may change, and I can’t find any other way
of doing it. Would somebody point me to what I am missing, please?

TIA,

Tim

Tim Rowe wrote:

I need to get at the character code used to represent a character. I
realise that “f”[0] will return the code for “f” (102), but I read in
a FAQ that this behaviour may change, and I can’t find any other way
of doing it. Would somebody point me to what I am missing, please?

Easy:

irb(main):002:0> ?f
=> 102

The ? operator is what you’re looking for:

irb(main):001:0> puts ?f
102
=> nil
irb(main):002:0>

-Mark

···

On Wed, Aug 20, 2003 at 12:42:20AM +0100, Tim Rowe wrote:

I need to get at the character code used to represent a character. I
realise that “f”[0] will return the code for “f” (102), but I read in
a FAQ that this behaviour may change, and I can’t find any other way
of doing it. Would somebody point me to what I am missing, please?

Sorry, I wasn’t completely clear. In my problem the character I want
to find the code for is (has to be!) in a variable.

foo = “f”
puts foo[0]

works at the moment, but may not continue to do so.

foo = “f”
puts ?foo

doesn’t work, of course!

···

On Tue, 19 Aug 2003 23:51:07 GMT, “Mark J. Reed” markjreed@mail.com wrote:

The ? operator is what you’re looking for:

irb(main):001:0> puts ?f
102

Ah, I misunderstood. Apologies.

I imagine that unpack will continue to work:

irb(main):042:0> foo = 'f'
=> "f"
irb(main):043:0> foo.unpack('C')[0]
=> 102

You can also use it to get the entire string as an array of character codes
in one fell swoop:

irb(main):045:0* foo = 'foo'
=> "foo"
irb(main):046:0> foo.unpack('C*')
=> [102, 111, 111]

There may be a better way of which I’m unaware. Actually, even if
there isn’t a better way at the moment, there probably will be at some
point before foo[0] stops working. :slight_smile:

-Mark

···

On Wed, Aug 20, 2003 at 11:46:42AM +0100, Tim Rowe wrote:

Sorry, I wasn’t completely clear. In my problem the character I want
to find the code for is (has to be!) in a variable.

foo = “f”
puts foo[0]

works at the moment, but may not continue to do so.

Ah, I misunderstood. Apologies.

No problem: my lack of clarity.

I imagine that unpack will continue to work:

irb(main):042:0> foo = ‘f’
=> “f”
irb(main):043:0> foo.unpack(‘C’)[0]
=> 102

That makes sense; thanks.

···

On Wed, 20 Aug 2003 13:19:49 GMT, “Mark J. Reed” markjreed@mail.com wrote: