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 Array Examples

Use string Arrays. See the syntax for initialization and iteration.
String array. Consider a book. It contains many words—thousands of strings that have meaning. For easy processing, we can store these strings in a string array.
With a string array, we can handle each word separately (with no parsing steps). In Ruby we often prefer iterators, not loops, to access an array's individual elements.StringArray
Create string arrays. Here we use 2 syntax forms to create string arrays. First, we use the initializer syntax—this requires only one line to create a 3-element array.

Length: A string array has a length. We access this property on the array itself. This property is fast.

Each: We use the each iterator to loop over the strings in the array. Modern Ruby programs typically use iterators like each.

Push: In the next part we use the push method to add elements in an imperative style.

Ruby program that creates string arrays # Initialize a three-element string Array. strings = ["one", "two", "THREE"] puts strings.length # Iterate over the strings with "each." strings.each do |st| puts st end # Create an array and push three strings to it. strings2 = Array[] strings2.push("one") strings2.push("two") strings2.push("THREE") # Write the length and display all the strings again. # ... Then use a shorter iterator syntax. puts strings2.length strings2.each {|st| puts st} Output 3 one two THREE 3 one two THREE
Read file lines, chomp. With IO.foreach we efficiently read in the lines of a file, one after another. We use chomp() to remove the trailing newline.File, IO.foreach
Contents, gems.txt: Ruby ruby sapphire diamond emerald topaz Ruby program that reads file into string array # Create an empty array. lines = [] # Use foreach iterator to loop over lines in the file. # ... Add chomped lines. IO.foreach("/files/gems.txt") do |line| lines.push(line.chomp()) end # Display elements in string array. lines.each do |v| print "[" << v << "]" << "\n" end Output [ruby] [sapphire] [diamond] [emerald] [topaz]
Combine string arrays. Two arrays can be concatenated with the plus operator. This is an effective way to combine two string arrays.

Note: This program, with a print() call instead of puts, can be run in Python or in Ruby.

Ruby program that combines two string arrays left = ["virus", "disease"] right = ["bacteria", "germ"] # Concatenate the two string arrays together. # ... The elements are placed together in a four-element array. result = left + right puts result Output virus disease bacteria germ
2D string array. This example creates a 2D string array and then iterates over it with the each iterator. It displays elements. It accesses a specific element in the top row.

Note: This is actually a "jagged array," an array of nested arrays. Length counts the nested arrays, not all elements, so it returns 2.

Ruby program that uses 2D string array # The first row. values1 = [] values1.push("AA") values1.push("BB") values1.push("CC") # The second row. values2 = [] values2.push("DD") values2.push("EE") values2.push("FF") # The 2D array (a container of the other arrays). container = [] container.push(values1) container.push(values2) # Use two iterators to display all strings in 2D array. container.each do |arr| arr.each do |inner| print inner << " " end print "\n" end # The 2D array has only two rows. puts container.length # Print string cell in middle of top row. puts container[0][1] Output AA BB CC DD EE FF 2 BB
Split and join strings. These methods involve string arrays. With join, we convert from a string array into a single string with a delimiter in between elements.

Split: This separates a string value based on a character. So split and join can "round-trip" data in their calls.

Split

Tip: In Ruby join() is an array method. It is called on an array. This is not true for Python, where join() acts on a string.

Ruby program that uses join, split items = ["two", "seven", "nine", "forty"] # Join the string array's elements together. # ... Display them. string_value = items.join(",") puts string_value # Split apart our newly-joined string. array_values = string_value.split(",") p array_values # We have four string elements. puts array_values.length Output two,seven,nine,forty ["two", "seven", "nine", "forty"] 4
Often, string arrays are converted into (and from) strings. File handling often involves string arrays. Ruby provides excellent syntax for these common tasks.Convert
© 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