ruby - 如何深度转换 Ruby 哈希值

标签 ruby hash transform

我有一个看起来像这样的散列:

hash = {
  'key1' => ['value'],
  'key2' => {
    'sub1' => ['string'],
    'sub2' => ['string'],
  },
  'shippingInfo' => {
                   'shippingType' => ['Calculated'],
                'shipToLocations' => ['Worldwide'],
              'expeditedShipping' => ['false'],
        'oneDayShippingAvailable' => ['false'],
                   'handlingTime' => ['3'],
    }
  }

我需要转换每个值,它是数组中的单个字符串,以便它最终像这样:

hash = {
  'key1' =>  'value' ,
  'key2' => {
    'sub1' => 'string' ,
    'sub2' => 'string' ,
  },
  'shippingInfo' => {
                   'shippingType' => 'Calculated' ,
                'shipToLocations' => 'Worldwide' ,
              'expeditedShipping' => 'false' ,
        'oneDayShippingAvailable' => 'false' ,
                   'handlingTime' => '3' ,
    }
  }

我找到了这个但无法让它工作 https://gist.github.com/chris/b4138603a8fe17e073c6bc073eb17785

最佳答案

比如:

def deep_transform_values(hash)
  return hash unless hash.is_a?(Hash)

  hash.transform_values do |val|
    if val.is_a?(Array) && val.length == 1
      val.first
    else
      deep_transform_values(val)
    end
  end
end

用类似的东西测试:

hash = {
  'key1' => ['value'],
  'key2' => {
    'sub1' => ['string'],
    'sub2' => ['string'],
  },
  'shippingInfo' => {
                   'shippingType' => ['Calculated'],
                'shipToLocations' => ['Worldwide'],
              'expeditedShipping' => ['false'],
        'oneDayShippingAvailable' => ['false'],
                   'handlingTime' => ['3'],
                   'an_integer' => 1,
                   'an_empty_array' => [],
                   'an_array_with_more_than_one_elements' => [1,2],
                   'a_symbol' => :symbol,
                   'a_string' => 'string'
    }
  }

给予:

{
  "key1"=>"value",
  "key2"=>{
    "sub1"=>"string",
    "sub2"=>"string"
  },
  "shippingInfo"=> {
    "shippingType"=>"Calculated",
    "shipToLocations"=>"Worldwide",
    "expeditedShipping"=>"false",
    "oneDayShippingAvailable"=>"false",
    "handlingTime"=>"3",
    "an_integer"=>1,
    "an_empty_array"=>[],
    "an_array_with_more_than_one_elements"=>[1, 2],
    "a_symbol"=>:symbol,
    "a_string"=>"string"
  }
}

根据您在评论中的问题,我想逻辑会有所改变:

class Hash
  def deep_transform_values
    self.transform_values do |val|
      next(val.first) if val.is_a?(Array) && val.length == 1
      next(val) unless val.respond_to?(:deep_transform_values)

      val.deep_transform_values
    end
  end
end

关于ruby - 如何深度转换 Ruby 哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55093966/

相关文章:

php - PHP伪随机有多随机,4个字节

css - compass 变换混合

html - 在 Chrome 上运行良好的 Css 3D 动画在 Safari 上不起作用

java - HashMap 不会按照默认值重新哈希

xml - 如何使用 XSLT-1.0 转换 xml 结构

ruby - 如果值存在则显示散列的内容

ruby - 使用 Nokogiri 库的永无止境的循环;不知道为什么

ruby - 从 ruby​​ 中的方法返回匿名对象

ruby - 测试结果整数是否在一个范围内的任何特殊断言

perl - 如何在Perl中按键对哈希的哈希排序?