Domanda

questa pagina wiki ha dato un'idea generale di come convertire un singolo carattere in ascii http: // en.wikibooks.org/wiki/Ruby_Programming/ASCII

Ma se ho una stringa e volevo estrarre l'ascii di ogni personaggio, cosa devo fare?

"string".each_byte do |c|
      $char = c.chr
      $ascii = ?char
      puts $ascii
end

Non funziona perché non è soddisfatto della riga $ ascii =? char

syntax error, unexpected '?'
      $ascii = ?char
                ^
È stato utile?

Soluzione

La variabile c contiene già il codice char!

"string".each_byte do |c|
    puts c
end

rendimenti

115
116
114
105
110
103

Altri suggerimenti

puts "string".split('').map(&:ord).to_s

Ruby String fornisce il metodo codepoints dopo 1.9.1.

str = 'hello world'
str.codepoints.to_a
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] 

str = "你好世界"
str.codepoints.to_a
=> [20320, 22909, 19990, 30028]

usa " x " .ord per un singolo carattere o " xyz " .sum per un'intera stringa.

Potresti anche chiamare to_a dopo each_byte o byte stringa # ancora migliori

=> 'hello world'.each_byte.to_a
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

=> 'hello world'.bytes
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
"a"[0]

o

?a

Entrambi restituirebbero il loro equivalente ASCII.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top