I have a bunch of Strings in an array in the form:
["name: hi", "pw: lol"]
How can I extract just the portion after the semi-colon and space in Ruby?
["name: hi", "pw: lol"].map{|x| x.split(': ')[1]}
produces:
["hi", "lol"]
The suggestions by Garrett and Peter will definitely do the trick. However, if you want, you can go a step further and easily turn this into a hash.
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:
map call we have the array [["name", "hi"], ["pw", "lol"]]Hash#[] takes a list of values that will be mapped as key, value, key, value,... As a result, we need to flatten the mapped array to pass to Hash#[]Since I don't know your exact needs I can't say whether you want a Hash or not, but it's nice to have the option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With