linux_sa
linux_sa

Reputation: 444

ruby collect first and last word from string

I have an array of strings with each string having arbitrary words and an arbitrary number of words. For each string, I need to collect only the first and last words. I can do first or last with:

a = vs.split("\n").
    select { |i| i =~ /^\s+\d/ }.
    collect { |i| i.scan(/\w+/).<first or last> }

but not for both first and last. Any suggestions?

Upvotes: 2

Views: 988

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118299

You can do the below also:

str = "I am a boy"
[str[/^\w+/],str[/\w+$/]]
# => ["I", "boy"]

Upvotes: 1

Stefan
Stefan

Reputation: 114248

Array#values_at should do the trick:

str = "a b c d e"
str.scan(/\w+/).values_at(0, -1)
#=> ["a", "e"]

Upvotes: 9

Related Questions