i have a bunch of texts in an array
["name: hi", "pw: lol"]
so i get each array. How can i just extract hi and lol ?
i have a bunch of texts in an array
["name: hi", "pw: lol"]
so i get each array. How can i just extract hi and lol ?
["name: hi", "pw: lol"].map{|x| x.split(': ')[1]}
produces:
["hi", "lol"]
You can loop through them and split them up by the :
like so:
["name: hi", "pw: lol"].each do |item|
puts item.split(":").last.lstrip
end
Example:
>> a = ["name: hi", "pw: lol"]
=> ["name: hi", "pw: lol"]
>> a.each do |item|
?> puts item.split(":").last.lstrip
>> end
>> 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.
I suggest you use Regular Expressions to process strings, although the previous answers work
a = ["name: hi", "pw: lol"]
a.map{|item| item.match(/\w+: ([\w\s]+)/)[1]}
this would output:
=> ["hi", "lol"]