ruby1.9 char to ascii(int value)

Posted by wxianfeng Wed, 26 Aug 2009 20:20:00 GMT

环境 : ruby 1.9.2 + ruby 1.8.7

ruby 1.8 时代 char to ascill 一般这么做:

"a"[0]  # 97
?a # 97

但是 1.9 时代 该方法 不可以了,输出如下:

"a"[0] # a
?a # a

后来 我用了 一个 变态的 方法:

"a".bytes.to_a.first # 97

1.9 时代 应该使用ord 函数

"a".ord  # 97
"a"[0].ord # 97
?a.ord # 97

ascill to char 通用:

97.chr # "a"

但是 ord 函数 1.8 环境下 同样可以使用;

看下 ord 函数的源码(built in 方法,内部看不到ruby代码):

  #     int.ord    => int
  #
  #
  # Returns the int itself.
  #
  #    ?a.ord    #=> 97
  #
  # This method is intended for compatibility to
  # character constant in Ruby 1.9.
  # For example, ?a.ord returns 97 both in 1.8 and 1.9.
  #
  #
  def ord
    # This is just a stub for a builtin Ruby method.
    # See the top of this file for more info.
  end

see:
http://stackoverflow.com/questions/1270209/getting-an-ascii-character-code-in-ruby-fails

This entry was posted on Wed, 26 Aug 2009 20:20:00 GMT and Posted in . You can follow any any response to this entry through the Atom feed. You can leave a comment or a trackback from your own site.

Tags


Trackbacks

Use the following link to trackback from your own site:
http://wxianfeng.com/trackbacks?article_id=138

Comments

  1. Avatar
    Italy - Greece over {{count}} years ago:

    I’m amazed, I have to admit. Seldom do I come across a blog that’s equally educative and amusing,
    and without a doubt, you’ve hit the nail on the head. The issue is something which
    not enough folks are speaking intelligently about. I amm very happy that I found
    this during my hunt ffor something regarding this.

  2. Avatar
    Italy - Greece over {{count}} years ago:

    I’m amazed, I have to admit. Seldom do I come acrooss a
    blog that’s equally educative and amusing, and without
    a doubt, you’ve hit the nail on the head. The issue is
    something which not enough folks aare speaking intelligently about.
    I amm vry happy that I found this duuring my hunt for
    something regarding this.

  3. Avatar
    http://sockserver.pusku.com/ over {{count}} years ago:

    Marvelous, what a web siute it is! This website provides useful information to us, keep it up.

Leave a comment