how to split a string between 2 parametres in ruby

62 Views Asked by At

Hi I try to separate input like this : <Text1><Text2><Text2>..<TextN> in a array who only have each text in each index, how I can use split with double parameters? I try make a double split but doesn't work:

request = client.gets.chomp
dev = request.split("<")
split_doble(dev)

dev.each do |devo|
  puts devo
end 

def split_doble (str1)
  str1.each do |str2|
    str2.split(">")
  end
end
2

There are 2 best solutions below

0
On

When you have a string like this

string = "<text1><text2><textN>"

then you can extract the text between the < and > chars like that:

string.scan(/\w+/)
#=> ["text1", "text2", "textN"]

/\w+/ is a regular expression that matches a sequence of word characters (letter, number, underscore) and therefore ignores the < and > characters.

Also see docs about String#scan.

0
On

In the string "<text1><text2><textN>" the leading < and ending > are in the way, so get rid of them by slicing them off. Then just split on "><".

str = "<text1><text2><textN>"
p str[1..-2].split("><") # => ["text1", "text2", "textN"]