Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: character to ascii from a string

Tags:

ruby

ascii

this wiki page gave a general idea of how to convert a single char to ascii http://en.wikibooks.org/wiki/Ruby_Programming/ASCII

But say if I have a string and I wanted to get each character's ascii from it, what do i need to do?

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

It doesn't work because it's not happy with the line $ascii = ?char

syntax error, unexpected '?'
      $ascii = ?char
                ^
like image 233
user2668 Avatar asked Sep 27 '08 15:09

user2668


People also ask

How do I convert a string to an array in Ruby?

The general syntax for using the split method is string. split() . The place at which to split the string is specified as an argument to the method. The split substrings will be returned together in an array.

How do you check if a character is a letter in Ruby?

You can read more in Ruby's docs for regular expressions. lookAhead =~ /[[:alnum:]]/ if you just want to check whether the char is alphanumeric without needing to know which.


4 Answers

The c variable already contains the char code!

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

yields

115 116 114 105 110 103 
like image 105
Konrad Rudolph Avatar answered Sep 29 '22 14:09

Konrad Rudolph


puts "string".split('').map(&:ord).to_s 
like image 26
alexsuslin Avatar answered Sep 29 '22 16:09

alexsuslin


use "x".ord for a single character or "xyz".sum for a whole string.

like image 39
Sh.K Avatar answered Sep 29 '22 14:09

Sh.K


Ruby String provides the codepoints method after 1.9.1.

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

str = "你好世界"
str.codepoints
=> [20320, 22909, 19990, 30028]
like image 42
LastZactionHero Avatar answered Sep 29 '22 16:09

LastZactionHero