Why there is no “.each” method for ruby strings?

Let’s consider the string “Hello\nWorld”. What is the result that you expect when  iterated  with .each method

“Hello\nWorld”.each do |element|
  puts elements
end

Do you expect to print out each character

H
e
l
l
o

W
o
r
l
d

or each line?

Hello
World

Pre 1.9, ruby strings used to have the .each method.
Guess what it used to do? iterate over each character? Or each line? 
Answer: each line! 

To avoid this confusion, from ruby 1.9, .each method has been discarded on ruby string. Instead, two separate methods .each_char and .each_line are introduced to iterate over each character and each line respectively. Additionally, .each_byte method is also available which will print ASCII value of each character

Happy coding

Leave a Reply

Your email address will not be published. Required fields are marked *