TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to RUBY

Ruby String Length, For Loop Over Chars

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.Iterator
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.

While, Until
Ruby program that uses string length, for loop # 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 end Output VALUE: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.String
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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf