Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get text between : and string?

Tags:

ruby

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?

like image 701
KJW Avatar asked Jun 22 '26 02:06

KJW


2 Answers

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

produces:

["hi", "lol"]
like image 94
Peter Avatar answered Jun 23 '26 15:06

Peter


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.

like image 36
Peter Wagenet Avatar answered Jun 23 '26 16:06

Peter Wagenet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!