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
^
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.
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.
The c
variable already contains the char code!
"string".each_byte do |c| puts c end
yields
115 116 114 105 110 103
puts "string".split('').map(&:ord).to_s
use "x".ord for a single character or "xyz".sum for a whole string.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With