Jonathan Silvestri Jonathan Silvestri - 6 months ago 7
Ruby Question

Search an Array containing strings of names, return names with length of X

Given an array

["Jim Bob", "Jim","Billy Bob"]
,

How do I return an array with all names whose length is X.

So, if I searched the array for names with a length of 2, I should return:
["Jim Bob", "Billy Bob"]


Looking to do this in Ruby.

Answer

Seems like you do not search names with a length of 2, but being composed of 2 names.

Select by the number of name parts:

["Jim Bob", "Jim", "Billy Bob"].select { |names| names.split.length == 2 }
#=> ["Jim Bob", "Billy Bob"]

Select by the number of spaces in the name:

["Jim Bob", "Jim", "Billy Bob"].select { |name| name.count(' ') == 1 }
#=> ["Jim Bob", "Billy Bob"]