Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在字符串数组中查找字符串的Ruby方法_Ruby - Fatal编程技术网

在字符串数组中查找字符串的Ruby方法

在字符串数组中查找字符串的Ruby方法,ruby,Ruby,我有一个字符串数组,如下所示: [noindex,nofollow] 或 [“索引”、“跟随”、“全部”] 我将这些称为“tags\u array”。我有一个如下的方法: return true if self.tags_array.to_s.include? "index" and !self.tags_array.to_s.include? "noindex" 但我认为有一种更聪明的方法来运行此代码,而不是将整个数组转换为字符串 问题是,有时信息以单个元素数组的形式出现,有时则以字符串数

我有一个字符串数组,如下所示:

[noindex,nofollow]
或 [“索引”、“跟随”、“全部”]

我将这些称为“tags\u array”。我有一个如下的方法:

return true if self.tags_array.to_s.include? "index" and !self.tags_array.to_s.include? "noindex"
但我认为有一种更聪明的方法来运行此代码,而不是将整个数组转换为字符串

问题是,有时信息以单个元素数组的形式出现,有时则以字符串数组的形式出现


关于最聪明的方法有什么建议吗?

您不必将数组转换为字符串,因为数组包含一个
include?
方法

tags_array.include?("index") #=> returns true or false
但是,正如您所说,有时信息以单个字符串的数组形式出现。如果该数组的单个字符串元素包含始终由空格分隔的单词,则可以使用该方法将该字符串转换为数组

或者如果单词总是用逗号分隔:

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

或者,如果您不知道它们之间将用什么分隔,但您知道这些单词只包含字母:

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

仅供参考,如果您在带有
的条件语句中使用
include?
等方法,那么您需要将
include?
的参数放在
等括号中。include?(“index”)
或者您可以取消该条件。谢谢您的提醒!我很感激。啊哈,使用分割法。我真的很喜欢这个策略。在我看来,似乎是赢家。谢谢你的建议!
tags_array[0].split(/[^a-zA-Z]/).include?("index") if tags_array.size == 1