develop with


Make an array of parts of a string based on a delimiter

Splitting is a way to separate a string based on a delimiter. A delimiter is the part of the string that marks how the string is structured. The default delimiter in ruby’s split method is a space.

For instance, in a comma delimited list (CSV), the string is divided into values based on a comma. If you wanted to split the string in ruby on the comma you would use a split method.

csv_string = "name, address, phone"
csv_values = csv_string.split(',')
csv_values.each { |value| puts value }

Split will accept a character / string delimiter as well as a regex delimiter. So, if you wanted to separate a string based on line breaks you could use regex for the split.

contents = "My Long Paragraph \n with various \n line breaks."
lines = contents.split(/\n/)
lines.each { |line| puts "Line: #{line}" }

comments powered by Disqus

Want to see a topic covered? create a suggestion

Get more developer references and books in the developwith store.