How do I get the text between: and a line?
5 answers
Garrett and Peter's suggestions will definitely do the trick. However, if you want, you can take it a step further and turn that into a hash easily.
values = ["name: hi", "pw: lol"]
hash = Hash[*values.map{|item| item.split(/\s*:\s*/)}.flatten]
# => {"name"=>"hi", "pw"=>"lol"}
There's a lot packed into the second line, so let me point out a few improvements:
- Separation allows flexibility in the colon, allowing any number of spaces both before and after.
- After the call
map
, we have an array[["name", "hi"], ["pw", "lol"]]
-
Hash#[]
takes a list of values to be displayed as key, value, key, value, ... As a result, we need to flatten the displayed array to go toHash#[]
Since I don't know your specific needs, I can't tell if you want Hash or not, but it's nice to have this option.
+4
source to share