morrime morrime - 1 year ago 80
Ruby Question

Ruby: How to select and copy a portion of string within an array?

Forgive me, I'm new!

I'm trying to select and copy a portion of a string from within an array; specifically, someone's last name.

array = ["Buffy Summers", "Willow Rosenberg", "Xander Harris", "Cordelia Chase", "Rupert Giles"]

I need to isolate and copy "Summers", "Rosenberg", "Harris", "Chase", and "Giles". Basically, I want to select everything after the space character through the end of the string.

I've seen this example:

irb> "truncate".gsub(/a.*/, '')
=> "trunc"

but this selects everything before the "a", while I need to select everything after a space character. Also, this is not within an array.

Answer Source

These piece of code will do the trick:

surnames = { |item| item.split(' ').last }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download