Ruby:如何显示字符串中每个字符的字符,十进制值和十六进制值

时间:2014-02-02 18:32:00

标签: ruby

如何显示字符串中每个字符的字符,十进制值和十六进制值

"hello test test"

3 个答案:

答案 0 :(得分:7)

我希望这不是功课吗?如果你遇到困难,可以向家庭作业寻求帮助,但请不要求完整的解决方案:除非你付出一些努力,否则你不会学到任何东西。

你需要这样的chars迭代器(或别名each_char

s = "hello test test"

s.chars do |c|
  puts "%s %3d %02X" % [ c, c.ord, c.ord ]
end

<强>输出

h 104 68
e 101 65
l 108 6C
l 108 6C
o 111 6F
   32 20
t 116 74
e 101 65
s 115 73
t 116 74
   32 20
t 116 74
e 101 65
s 115 73
t 116 74

答案 1 :(得分:0)

每个角色都使用String#chars

[72] pry(main)> "hello test test".chars
=> ["h", "e", "l", "l", "o", " ", "t", "e", "s", "t", " ", "t", "e", "s", "t"]

每个字符的十进制值使用String#ord

[73] pry(main)> "hello test test".chars.map(&:ord)
=> [104, 101, 108, 108, 111, 32, 116, 101, 115, 116, 32, 116, 101, 115, 116]

ASCII hex

[84] pry(main)>"hello test test".chars.map { |x| x.ord.to_s(16) }
=> ["68","65","6c","6c","6f","20","74","65","73","74","20","74","65","73","74"]

答案 2 :(得分:0)

'hello test test'.each_char { |c| puts "#{c} => #{c.hex} => #{c.ord}" }