How do I get the text between: and a line?

I have a group of strings in an array in the form:

["name: hi", "pw: lol"]

How can I extract only part after comma and space in Ruby?

+2


source to share


5 answers


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

      

gives:



["hi", "lol"]

      

+7


source


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 to Hash#[]

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


You can skip them and split them :

as follows:

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

      

+1


source


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 outputs:

=> ["hi", "lol"]

+1


source


a.to_s
     h=hi~=a

a.index[h].value

      

or

hi{1}

      

0


source







All Articles