【问题标题】:Include method in Ruby applied on an ArrayRuby 中的 Include 方法应用于数组
【发布时间】:2020-07-16 10:02:14
【问题描述】:

我遇到了包含问题?红宝石中的方法。据我了解,如果数组包含指定的元素,此方法应返回 true。像这样:

a = [ "a", "b", "c" ]
a.include?("b")   #=> true
a.include?("z")   #=> false`

但是当我这样做时:

soap_opera = ["all", "my", "children"]
p soap_opera.include?("a")

它返回假。为什么?

【问题讨论】:

    标签: arrays ruby methods


    【解决方案1】:

    我遇到了包含问题?红宝石中的方法。据我了解,如果数组包含指定元素,此方法应返回 true。

    没错。

    但是当我这样做时:

    soap_opera = ["all", "my", "children"]
    p soap_opera.include?("a")
    

    它返回假。为什么?

    因为,正如你上面所说的:

    如果数组包含指定元素,此方法应返回 true

    soap_opera 颂歌不包含元素"a"soap_opera 包含三个元素,"all""my""children""a" 不在其中。

    【讨论】:

      【解决方案2】:

      正如已经解释的那样,这是因为您的字符串数组不包括字符串 'a'

      如果结果为true,则数组还应列出字符串'a'例如

      ary = ['not', 'a', 'dog']
      ary.include? 'a' #=> true
      


      如果你想检查if any数组的字符串是否包含子字符串'a',那么你可以使用Enumerable#any?
      ary = ["all", "my", "children"]
      ary.any? { |str| str.include? 'a' } #=> true
      


      而如果您想检查是否所有字符串都包含子字符串'a',那么您可以使用Enumerable#all?
      ary = ["all", "my", "children"]
      ary.all? { |str| str.include? 'a' } #=> false
      

      【讨论】:

        【解决方案3】:

        您在寻找字符“a”吗?如果你是,你可以试试这个:

        joined_soap_opera = soap_opera.join #  => "allmychildren" 
        
        joined_soap_opera.include?("a") #  => true 
        

        【讨论】:

          【解决方案4】:

          您似乎混淆了Array#include?String#include?

          您可以单独检查每个元素,而不是检查整个数组:

          oap_opera = ["all", "my", "children"]
          
          oap_opera.each do |element|
            if element.include?("a")
              puts "'#{element}' includes 'a'"
            else
              puts "'#{element}' does not include 'a'"
            end
          end
          

          打印

          'all' includes 'a'
          'my' does not include 'a'
          'children' does not include 'a'
          

          【讨论】:

            猜你喜欢
            • 2011-12-09
            • 2011-09-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-05-02
            • 2013-07-31
            • 1970-01-01
            • 2015-12-31
            相关资源
            最近更新 更多