morrime morrime - 4 months ago 8
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

These piece of code will do the trick:

surnames = array.map { |item| item.split(' ').last }
Comments