Skip to content

Instantly share code, notes, and snippets.

@mediafinger
Created February 20, 2020 22:49
Show Gist options
  • Save mediafinger/8499cb6ffaee70bfd7c524565ee64b7f to your computer and use it in GitHub Desktop.
Save mediafinger/8499cb6ffaee70bfd7c524565ee64b7f to your computer and use it in GitHub Desktop.
Split a String at a "line-break" character in Ruby
# Task:
# implement different ways to split a string at a line-break character into lines
# for the sake of simplicity these examples use "0" as "line-break" character
# this solves only a part of the task recursivly
def detect_first_line(string, line = "", position = 0)
return line if string[position] == "0"
puts "#{position}, #{string[position]}, #{line}"
detect_first_line(string, line + string[position], position + 1)
# puts "#{position}, #{string[position]}, #{line}" # comment this in and inspect the output
end
# => detect_first_line("germany0spain0sweden")
def split_recursive(string, position = 0, lines = [], line_number = 0)
# when it finds a line-break character, it skips it and increments the line_number
return split_recursive(string, position + 1, lines, line_number + 1) if string[position] == "0" # remove the "return", run the code and inspect the output
lines[line_number] = lines[line_number].to_s + string[position] # for each new line the array is empty and nil.to_s => ""
puts "#{position}, #{string[position]}, #{lines}"
return lines if position == string.length - 1
split_recursive(string, position + 1, lines, line_number)
end
# => split_recursive("germany0spain0sweden")
def split_for_loop(string)
lines = []
line_number = 0
for position in 0..(string.length - 1) do
if string[position] == "0"
line_number += 1
next
end
lines[line_number] = lines[line_number].to_s + string[position]
puts "#{position}, #{string[position]}, #{lines}"
end
lines
end
# => split_for_loop("germany0spain0sweden")
def split_enumerator(string)
lines = []
line_number = 0
string.each_char do |c|
if c == "0"
line_number += 1
next
end
lines[line_number] = lines[line_number].to_s + c
puts "#{c}, #{lines}"
end
lines
end
# => split_enumerator("germany0spain0sweden")
# idiomatic Ruby
"germany0spain0sweden".split("0")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment