OneBite.Dev - Coding blog in a bite size

split a string by a delimiter in Ruby

Code snippet on how to split a string by a delimiter in Ruby

  str = "Hello world"
  str.split(" ")

This code will take a string, in this case “Hello world”, and separate it into two strings based on the delimiter, which is a single space in this example. The variable “str” is first set to the original string. Then the built-in Ruby method “split” is called on the variable, passing in the delimiter as a parameter. This will give us an array with two strings, one with the text before the delimiter and one with the text after. In this example, the returned array would contain [“Hello”, “world”].

ruby