简体   繁体   中英

Ruby method to find a string within an array of strings

I've got an array of strings that looks like this:

[noindex,nofollow]

or ["index", "follow", "all"]

I'm calling these "tags_array." I've got a method that looks like this:

return true if self.tags_array.to_s.include? "index" and !self.tags_array.to_s.include? "noindex"

But I think there's a smarter way to run this code than to take the entire array and convert it to an string.

The problem is, sometimes the info comes in as a single element array and other times it comes in as an array of strings.

Any suggestions on the smartest way to do this?

You wouldn't have to convert your Array into a String since Array contains an include? method.

tags_array.include?("index") #=> returns true or false

However, like you said, sometimes the info comes in as an Array of a single String. If the single String element of that Array contains words that are always separated by a space then you could turn the String into an Array with the split method.

tags_array[0].split.include?("index") if tags_array.size == 1 

Or if the words are always separated with commas:

tags_array[0].split(",").include?("index") if tags_array.size == 1 

EDIT:

Or if you have no idea what they will be separated by but you know the words will only ever contain letters:

tags_array[0].split(/[^a-zA-Z]/).include?("index") if tags_array.size == 1 

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