【问题标题】:Return array of hashes based on hash element match根据哈希元素匹配返回哈希数组
【发布时间】:2013-01-27 12:39:19
【问题描述】:

我想知道如何搜索散列数组并根据搜索字符串返回一个值。例如,@contacts 包含哈希元素::full_name:city:email。变量@contacts(我猜它是一个数组)包含三个条目(可能是行)。以下是我迄今为止根据:city 值进行搜索的代码。但是它不起作用。谁能告诉我发生了什么?

def search string
  @contacts.map {|hash| hash[:city] == string}
end

【问题讨论】:

    标签: ruby hash


    【解决方案1】:

    您应该使用select 而不是map

    def search string
      @contacts.select { |hash| hash[:city] == string }
    end
    

    在您的代码中,您尝试使用块来map(或转换)您的数组,这会产生布尔值。 map 接受一个块并为self 的每个元素调用该块,构造一个包含该块返回的元素的新数组。结果,你得到了一个布尔数组。

    select 工作类似。它需要一个块并迭代数组,但不是转换源数组,而是返回一个数组,其中包含块返回true 的元素。所以这是一种选择(或过滤)方法。

    为了了解这两种方法之间的区别,查看它们的示例定义很有用:

    class Array
      def my_map
        [].tap do |result|
          self.each do |item|
            result << (yield item)
          end
        end
      end
    
      def my_select
        [].tap do |result|
          self.each do |item|
            result << item if yield item
          end
        end
      end
    end
    

    示例用法:

    irb(main):007:0> [1,2,3].my_map { |x| x + 1 }
    [2, 3, 4]
    irb(main):008:0> [1,2,3].my_select { |x| x % 2 == 1 }
    [1, 3]
    irb(main):009:0>
    

    【讨论】:

    • 这行得通。但是,在您的回答中,此语法是否基本上告诉程序将每个元素分开以进行检查: { |hash|哈希[:city] == 字符串}
    • @NealR,是的,这是块的语法,即为数组的每个项目调用的一段代码(如果将块传递给select)。生成的数组将仅包含块中包含 true 的那些项目。
    【解决方案2】:

    你可以试试这个:

     def search string
        @contacts.select{|hash| h[:city].eql?(string) }
     end
    

    这将返回一个匹配字符串的哈希数组。

    【讨论】:

      猜你喜欢
      • 2014-07-12
      • 2018-06-14
      • 2015-11-13
      • 2019-10-10
      • 2021-08-19
      • 1970-01-01
      • 2021-11-19
      • 2022-01-14
      • 2020-12-08
      相关资源
      最近更新 更多