Ruby/String/split

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

Версия от 17:10, 26 мая 2010; (Обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

Convert a string to a hash

text = "The rain in Spain falls mainly in the plain."
word_count_hash = Hash.new 0
p word_count_hash
text.split(/\W+/).each { |word| word_count_hash[word.downcase] += 1 }
p word_count_hash
# => {"rain"=>1, "plain"=>1, "in"=>2, "mainly"=>1, "falls"=>1,
#     "the"=>2, "spain"=>1}



Paragraphs counter by split method

text = %q{
This is a test of
paragraph one.
This is a test of
paragraph two.
This is a test of
paragraph three.
}
puts text.split(/\n\n/).length



split a string into multiple pieces

puts "Short sentence. Another. No more.".split(/\./).inspect



Split a string, reverse the sequence and append them again

s = "order. wrong the in are words These"
s.split(/(\s+)/).reverse!.join("")   # => "These words are in the wrong order."



split method can split on newlines, or multiple characters at once, to get a cleaner result

puts "Words   with  lots of   spaces".split(/\s+/).inspect



Split one by one

"0123456789".split # => ["0123456789"]
"0123456789".split( // ) # => ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]



Splitting Strings into Arrays with scan

puts "This is a test".scan(/\w/).join(",")



Split with by one or more space

"Three little       words".split(/\s+/)   # => ["Three", "little", "words"]