Convert a string to array in Ruby using split method

The split() function can be used in Ruby to convert a string to an array by following the defined pattern. It is an easier way to convert the string to an array. Ones can alter a string into multiple substrings by using this method.

In addition, a string can be cut into individual segments in this manner. You can split the string into parts that are based on words, spaces, and characters.

Syntax

array= string.split( pattern, limit) public

Parameters

  • pattern: It can either be a string or a regular expression.  If the pattern is a string or regExp, a string will be subdivided where this pattern matches.
  • limit: It shows the maximum number of entries allowed in the array.

Return value

array: An array of sub-string(s) will be returned as per the defined parameters.

Explanation

In the below-mentioned example, we are defining a code that will divide the string parts based on the white spaces between words.

string1 = "We are using a split method for converting a string into parts"
print string1.split()
  • Line#1: Defining a string.
  • Line#2: Invoking string1.split() method in ruby to split a string into an array of sub-strings with the default termination character is space.

Output

convert a string to an array in Ruby
convert a string to an array in Ruby

We can also split the string into an array of individual characters by using the following code.

string2 = "AlgoIdeas"
print string2.split("")

  • Line#1: Defining a string with "AlgoIdeas" as value.
  • Line#2: Invoking string2.split("") to split called string values character by character.

Output

convert a string to an array in Ruby
convert a string to an array in Ruby

A string can also be subdivided based on any specified word as mentioned in the following example.

string1 = "We are using a split method for converting a string into parts"
print string1.split("for")
  • Line#1: Defining a string string1.
  • Line#2: Invokling string1.split() with argument "for" to split when "for" will be encountered.

Output

convert a string to an array in Ruby
convert a string to an array in Ruby

Stay in the Loop

Get the daily email from Algoideas that makes reading the news actually enjoyable. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

- Advertisement -

You might also like...