根据条件迭代哈希

时间:2017-01-24 04:18:46

标签: ruby

colors = [
  ["blue","red","green"],
  ["yellow","red","green"],
  ["orange","red"]
]

elements =[
  {"sun"=>"yellow"},
  {"sky"=>"blue"},
  {"ocean"=>"blue"},
  {"pumpkin"=>"orange"}
]

如何迭代colors数组以检查对象的哈希值中是否存在值,并产生此结果?

[["sun","yellow"], ["sky","blue"], ["ocean","blue"], ["pumpkin","orange"]]

2 个答案:

答案 0 :(得分:0)

要从对象中选择项目,请使用array#select方法:

elements.select{|el|colors.flatten.include? el.values[0]} # => [{"sun"=>"yellow"}, {"sky"=>"blue"}, {"ocean"=>"blue"}]

让我为你打破这段代码:

  1. elements.select遍历您的数组
  2. flatten只展平您的颜色数组:[['a', 'b'], 'c'].flatten为您提供['a', 'b', 'c']
  3. 如果您的值在数组中,
  4. array#include? i将返回true

    然后您可以将其转换为[key, value]数组执行

    的数组
    filtered_elements.map(&:to_a)
    

    这是在数组的每个对象上调用object#to_a方法

答案 1 :(得分:0)

我认为

private func http(request: URLRequest){
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: self, delegateQueue: .main)
        /*Tweaking*/
        let task = session.uploadTask(with: request, from: request.httpBody!)
        task.resume()
    }

如果单个值是request.setValue("multipart/form-data; boundary=\(yourboundary)", forHTTPHeaderField: "Content-Type") 元素之一的元素,那么objects =[{ "sun"=>"yellow" }, { "sky"=>"blue" }, { "ocean"=>"blue" }, { "pumpkin"=>"orange" }] 的每个元素都将被保留并转换为扁平数组,其中

objects

可以写下以下内容。

colors

请注意

colors =[["blue", "red", "green"], ["yellow", "red", "green"],  ["orange", "red"]]

第二个例子(ucolors = colors.flatten.uniq #=> ["blue", "red", "green", "yellow", "orange"] objects.flat_map(&:to_a).select { |_,c| ucolors.include? c } #=> [["sun", "yellow"], ["sky", "blue"], ["ocean", "blue"], ["pumpkin", "orange"]] 未更改):

objects.flat_map(&:to_a)
  #=> [["sun", "yellow"], ["sky", "blue"], ["ocean", "blue"], ["pumpkin", "orange"]]