close
昨晚又失眠了...
唉...

然後順便想著...
In Ruby, integer can use method 'chr' to convert to the character
but If I want to convert charactor to integer, how can I do?

我記得以前有用過,可是我忘了
一直找不到那個method可以轉換
所以剛剛上了irc://irc.freenode.net/ #ruby-lang
問了一下...
一開始,我並不知道有這method... 所以我自己寫了個
But I don't know how can I get the value...

Following is the chatting log in the channel...

zusocfc: Hi, all
zusocfc: Excuse me.. I want to do a meta programming...
zusocfc: I want to re-define the Integer class, add a method named "asc"
kmeyer: class Integer; def asc;
zusocfc: And I don't know how to get the integers
zusocfc: kmeyer: I know that, I mean I want to do like..
zusocfc: kmeyer:  puts 65.asc # Output "A"
kmeyer: oh.
kmeyer: You want chr
kmeyer: 65.chr # "A"
zusocfc: Orz.. wait
zusocfc: =  ="
zusocfc: puts "A".asc # Output 65
kmeyer: "A".ord
zusocfc: ....
kbrooks: no
kmeyer: err
kmeyer: wait
kbrooks: "A"[0]
kmeyer: "A"[0]
kmeyer: or ?A
zusocfc: ha! Thanks a lot :D
kmeyer: no prob
zusocfc: but.. If I want to add a method for practice like that, how can I do?
zusocfc: kmeyer: uh... it return 0
zusocfc: returned*
kmeyer: "a".asc ?
kmeyer: then swap out [0] for self[0]
zusocfc: kmeyer: got it.. thanks :D
zusocfc: kmeyer: excuse me... I have a problem... now there has a code "65.chr", how chr gets the value '65'?
kmeyer: it's smart :P
kmeyer: err
zusocfc: kmeyer: err...
kmeyer: chr is a method on Fixnum
kmeyer: self
kmeyer: but it's actually in C
zusocfc: kmeyer: OK!! Thank you :D

ya~ you can use "self" to get the value, and '?' or '[0]' can get the ASCII code of the character!
But, it could not be use when I input a string...
So... I have to write a member funtion for class String that convert each character in a string to ascii code...
Following is the source code...

class String

  def each_asc
    ascii = Array.new
    self.size.times do |c|
      ascii[c] = self[c]
    end
    ascii
  end

end


Usage:

puts "ABCD".each_asc

It will output:
65
66
67
68

arrow
arrow
    全站熱搜

    hechian 發表在 痞客邦 留言(0) 人氣()