5

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?

2
  • 1
    FYI, if you are using methods like include? in a conditional statement with an and or or then you'll want to put the argument of include? in parentheses like .include?("index") or else you could throw off the condition. Commented Jun 28, 2012 at 19:07
  • Thanks for mentioning that! I appreciate it. Commented Jun 28, 2012 at 19:43

1 Answer 1

7

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Aha, using the split method. I really like that strategy. Looks like the winner to me. Thank you for your suggestion!

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.