Ruby String Length, For Loop Over CharsUse the length property on a string. Iterate over the characters in a string with loops.
String length. A string has a certain number of characters—this is its length. In Ruby we access the length property. We can use length in a for-loop or while-loop to access chars.
For most Ruby programs,
using an iterator (like each_char) to access elements (like chars in a string) is best. But the length property, and a for-loop, can be used as well.
An example program.
Let us review the length property. With the string "ABC" it returns the value 3—the string has 3 characters in it.
For We use a for-loop over the string to iterate over the chars in forward order. We access each char by its index.
While We can use a while-loop to iterate over the string in a reverse (backwards) order. We begin at length minus one.
# An input string.
Ruby program that uses string length, for loop
value = "ABC"
# Display the string.
# Loop over characters in the string forwards.
i in 0..value.length
puts "CHAR FORWARD:"
# Loop over characters backwards.
temp = value.length
temp >= 0
puts "CHAR BACKWARD:"
temp -= 1
String length is important in Ruby. This high-level language hides a lot of the complexity of things. With iterators (like each_char) we hide complexity when looping over chars.
For the greatest level of control, though, for-loops (and similar loops) are sometimes needed. We can access adjacent chars, or modify the index as we go along.