Ruby/String/char range

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

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

Содержание

iterate over all the characters using a block

thoreau = "asdfasdfasdf"
 
thoreau.each_byte do |c|
  print c.chr, "/"
end



Range indexes are negative

#!/usr/bin/env ruby
thoreau = "If a man does not keep pace with his companions, perhaps it is because he hears a different drummer."
puts thoreau[-8..-2] # => "drummer"



Retrieve part of a string with the [] method, using a range.

thoreau = "qwerqwerqwerqwerqwer"
puts thoreau[7..9]



starting at the end of the string using negative numbers, get the second to last character through the eighth to last

thoreau = "asdfasdfasdfadsfasdfasdfadsf"
 
puts thoreau[-8..-2]