Jonathan Silvestri Jonathan Silvestri - 1 year ago 48
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 Source

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"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download