-3

I have a list of names in an array in Ruby:

names = ["John Smith","Bob Miller"]

So I want to do a regex and get this array:

namesRegex = ["JS","BM"]

This is, I extract the uppercase characters from the string, merge them and put them in a new array.

Any help is appreciated.

Tripon
  • 81
  • 1
  • 10

2 Answers2

1

This is really simple:

names.map { |name| name.gsub(/[^A-Z]/, '') }

You could very readily construct a less elegant but wholly valid solution to this problem that doesn't even require the use of regular expressions or mapping.

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
coreyward
  • 77,547
  • 20
  • 137
  • 166
  • Thanks for the solution. It happens that my lack of experience with the .map function was preventing me to implement the regex for the whole array. – Tripon May 25 '14 at 00:12
0
 names.map { |name| name.scan(/\b\w/).*'' }
bluexuemei
  • 233
  • 3
  • 12