Ruby/String/each byte

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
м (1 версия)
 

Текущая версия на 17:56, 13 сентября 2010

Содержание

Append the output to an array

out = [] 
"myValue".each_byte { |b| p out << b} 
p out



Convert each decimal to its character equivalent with Integer"s chr method

"myValue".each_byte { |b| print b.chr, "/" }



each_byte block logics

#!/usr/bin/env ruby
thoreau = "If a man does not keep pace with his companions, perhaps it is because he hears a different drummer."
thoreau.each_byte do |c|
  print c.chr, "/"
end



each_byte takes a string apart byte by byte, returning the decimal value for the character at each index location.

"myValue".each_byte { |b| print b, "/" }



Loop through each byte from a string

hexadecimal = "\x00\x01\x10\x20"
hexadecimal.each_byte { |x| puts x }



Use case to deal with special key

def snoop_on_keylog(input)
  input.each_byte  do |b|
    case b
      when ?\C-c; puts "Control-C: stopped a process?"
      when ?\C-z; puts "Control-Z: suspended a process?"
      when ?\n;   puts "Newline."
      when ?\M-x; puts "Meta-x: using Emacs?"
    end
  end
end
snoop_on_keylog("ls -ltR\003emacsHello\012\370rot13-\012\032")