简体   繁体   中英

Ruby split array then return first element based on pattern

I have a languages string, defined as: en,fr,nl_nl . I need to return the first element that starts with nl . How can I do this?

I've started with languages.split(',') , but don't know what's the best way to search for a pattern in an array and return the first element.

This should work as you expect:

languages.split(',').detect { |s| s.start_with?('nl') }
# => "nl_nl"

Unless you need the array, you could use a regular expression to find the substring:

languages = 'en,fr,nl_nl'
languages[/\bnl[^,]*/] #=> "nl_nl"
languages[/\ben[^,]*/] #=> "en"

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