Ruby/String/each char

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

Перейти к: навигация, поиск

Enumerate each character as a 1-character string

s = "A\nB"                       # Three ASCII characters on two lines
# This does not work for multibyte strings in 1.8
# It works (inefficiently) for multibyte strings in 1.9:
0.upto(s.length-1) {|n| print s[n,1], " "}



Sequentially iterate characters as character strings

s = "A\nB"                       # Three ASCII characters on two lines
# Works in Ruby 1.9, or in 1.8 with the jcode library:
s.each_char { |c| print c, " " } # Prints "A \n B "



Use each_char with multibyte chars

s = "¥1000"
s.each_char {|x| print "#{x} " }         # Prints "¥ 1 0 0 0". Ruby 1.9
0.upto(s.size-1) {|i| print "#{s[i]} "}  # Inefficient with multibyte chars