0

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:

"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.

0

2 Answers 2

4

These piece of code will do the trick:

surnames = array.map { |item| item.split(' ').last }
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, unless you're sure, that global vairiable $; has it's default value. ruby-doc.org/core-2.2.0/String.html#method-i-split
-1

Implementing something similar to your suggestion, we have:

array.map { |s| s.gsub(/\w+\s+/,'') }                                       
#=> ["Summers", "Rosenberg", "Harris", "Chase", "Giles"]

or

array.map {|s| s.match(/\w+\z/).to_s }
#=> ["Summers", "Rosenberg", "Harris", "Chase", "Giles"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.