tags:

views:

118

answers:

4

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 ?

+7  A: 
["name: hi", "pw: lol"].map{|x| x.split(': ')[1]}

produces:

["hi", "lol"]
Peter
If you are not sure if there's always one and only one space after the :, you can split on ':' and then use .strip to remove any whitespace.
J. Pablo Fernández
+1  A: 

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
Garrett
+4  A: 

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:

  • The split allows for flexibility in the colon, allowing for any number of spaces both before and after.
  • After the 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.

Peter Wagenet
+1  A: 

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"]

Omar Qunsul