简体   繁体   中英

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?

Array#values_at should do the trick:

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

You can do the below also:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM