【问题标题】:Ruby - return boolean for matching one or both elements in an array elementRuby - 返回布尔值以匹配数组元素中的一个或两个元素
【发布时间】:2021-01-30 14:02:42
【问题描述】:

我有一个由字符串组成的数组,其中的文本用逗号分隔。我需要返回一个布尔值,指示它是否为空,或者其他两个字符串中的一个或两个是否是数组元素中包含的唯一值。

text1 = John
text2 = Doe

array1['element'] = 'John, Doe' #true
array2['element'] = 'Bob, Buck' #false
array3['element'] = 'John, Buck' #false
array4['element'] = 'John' #true
array5['element'] = 'John, John' #true
array6['element'] = '' #true

我可以一次匹配一个或一个空元素,但我不确定如何确保包含我的匹配项而不包含其他文本。

foo = 'John,Doe,Buck'

    if foo['John'] 
            foo <= 'Set to Repeat'     
         elsif foo['Doe']
            foo <= 'Set to Repeat'
         elsif foo['John,Doe']
            foo <= 'Set to Repeat'
         elsif foo['']
            foo <= 'Set to Repeat'
         else foo
         end

使用此代码我得到一个匹配项,但由于存在“Buck”,我需要拒绝它。

【问题讨论】:

  • 你真的应该发布你到目前为止所拥有的代码,以获得真正的帮助。此外,请发布示例,说明您如何没有得到您期望/想要的。
  • 添加了一个粗略的示例代码sn-p
  • 我不明白你为什么要比较 foo'Set to Repeat'foo[some_string] 语法仅用于检查是否存在确切的子字符串,因此它不是正确的操作(您必须检查所有可能的排序!)。研究迭代、String.split、数组运算符-&amp; 以及集合和集合操作等概念。
  • &lt;= 应该是什么?你的意思是“添加到数组”?其中很多看起来像 Ruby 风格的伪代码,实际上并没有什么帮助。尝试输入实际代码。
  • 你的问题出在前两行:JohnDoe 这两个常量是未定义的,所以你会得到一个NameError 异常。

标签: arrays ruby string string-matching


【解决方案1】:

这个问题有点令人困惑,因为如果array 是一个数组,array1['element'] 是无效的。方法Array#[] 必须采用一个整数、两个整数或一个范围作为其参数。给它一个字符串参数将引发异常 (TypeError (no implicit conversion of String into Integer)。

假设:

text = ['John', 'Doe']
arr = ['John,    Doe', 'Bob, Buck', 'John ,  Buck', 'John', 'John, John', '']

并且您想知道arr(字符串)的哪些元素仅包含数组text 中的单词。你可以这样做。

arr.map { |s| s.split(/ *, +/).all? { |ss| text.include?(ss) } }
  #=> [true, false, false, true, true, true]

如果,例如,s = 'Bob, Buck',那么

s.split(/, +/)
  #=> ["Bob", "Buck"]

同样,

'Bob'.split(/, +/)
  #=> ["Bob"] 
''.split(/, +/)
  #=> [] 
 

请参阅String#splitArray#all?Array#include?正则表达式 / *, +/ 表示“匹配零个或多个 (*) 空格,后跟一个逗号,后跟一个或多个 (+) 空格”。 (如果允许'John,Doe' 使用/ *, */。)

也可以写

arr.map { |s| s.split(',').all? { |ss| text.include?(ss.strip) } }
  #=> [true, false, false, true, true, true] 

这里

'John ,  Buck'.split(',')
  #=> ["John ", "  Buck"]

然后

"John ".strip
  #=> "John"
"  Buck".strip
  #=> "Buck"

String#strip

您可能想知道为什么我使用Array#all? 考虑到all? 的接收者是一个仅包含两个元素的数组(例如a = ['John', 'Doe']。这仅仅是因为将a 视为一个数组更容易任意大小,而不是让一个语句需要text 包含a[0] 和另一个需要text 包含a[1]

最后,另一个变体是使用String#scan

arr.map { |s| s.scan(/[, ]+/).all? { |ss| text.include?(ss) } }
  #=> [true, false, false, true, true, true] 

scan 接受一个参数,它是一个正则表达式,其内容为“匹配一个或多个 (+) 字符,每个字符不是 (^)逗号或空格”。括号表示一个字符类,意味着一个字符必须匹配类中的任何字符。类定义开头的^ 表示“后面的字符除外”。

【讨论】:

    猜你喜欢
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 2014-07-30
    相关资源
    最近更新 更多