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 input string.
value = "ABC"# Display the string.
puts "VALUE:" << value
puts "LENGTH:" << String(value.length)
# Loop over characters in the string forwards.
for i in 0..value.length - 1
puts "CHAR FORWARD:" << value[i]
end
# Loop over characters backwards.
temp = value.length - 1
while temp >= 0
puts "CHAR BACKWARD:" <> value[temp]
temp -= 1
endVALUE:ABC
LENGTH:3
CHAR FORWARD:A
CHAR FORWARD:B
CHAR FORWARD:C
CHAR BACKWARD:C
CHAR BACKWARD:B
CHAR BACKWARD:A
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 23, 2021 (image).