【问题标题】:How do I convert hash symbols [closed]如何转换哈希符号 [关闭]
【发布时间】:2016-12-30 08:15:35
【问题描述】:

我有一个哈希:

{:name=>"testname", :data=>"[209.04, 110.97, 38.83, 234.18]"}

我想把它转换成:

{name: "testname", data: [209.04, 110.97, 38.83, 234.18]}

【问题讨论】:

  • 两个哈希版本在 Ruby 中是相同的。你为什么要改变这个?你想达到什么目标?关于字符串中的数组,假设data字符串总是包含有效的JSON?
  • hash[:data] = eval(hash[:data]) ?但是,eval 操作并不安全,会导致很多恶意攻击。
  • 我想在高柱形图中以第二种格式部署值。
  • 系列块需要第二种格式的值
  • 您需要 JSON 作为输出吗?你能在问题中这样说吗?

标签: ruby regex hash


【解决方案1】:

我觉得你想把你的 Ruby 数组翻译成 JavaScript:

require 'json'

# parse the string to get the included JSON
hash = { :name => "testname", :data => "[209.04, 110.97, 38.83, 234.18]" }
hash[:data] = JSON.parse(hash[:data])

# hash look like this now
# { :name => "testname" , :data => [209.04, 110.97, 38.83, 234.18] }

# translate to json to use with highchart:
hash.to_json
#=> { "name": "testname", "data": [209.04,110.97,38.83,234.18] }

【讨论】:

    【解决方案2】:

    当你说你想创建类似的东西时

    [209.04, 110.97, 38.83, 234.18]
    

    您首先需要决定您希望数字具有什么数据类型。如果您只是用 Ruby 编写 209.04,则类型为 Float,但根据您要对数据执行的操作,您可能会考虑改用 BigDecimal

    这是获取浮点数数组的解决方案:

    myhash = {:name=>"testname", :data=>"[209.04, 110.97, 38.83, 234.18]"}
    myhash[:data] = myhash[:data][1..-2].split(/,\s*/).map(&:to_f)
    

    如果您更喜欢 BigDecimal,它会是这样的:

    require 'bigdecimal'
    myhash = {:name=>"testname", :data=>"[209.04, 110.97, 38.83, 234.18]"}
    myhash[:data] = myhash[:data][1..-2].split(/,\s*/).map { |string| BigDecimal.new(string) }
    

    【讨论】:

      【解决方案3】:

      您的问题并不太清楚,看起来您不了解 Ruby 的哈希值以及它们的显示方式。调解这些:

      hash = {a:1}
      hash # => {:a=>1}
      

      hash 有一个符号 :a 作为其键。检查时,Ruby 使用=> 表示法显示哈希,因此{a:1} 显示为{:a => 1}。这是相同的哈希,只是第二种是显示它们的原始方式,适用于符号和非符号键:

      hash = {a:1, 'b' => 2}
      hash # => {:a=>1, "b"=>2}
      

      继续……

      转换:data 值可以通过多种方式完成,但我会这样做:

      hash = {name: "testname", data: "[209.04, 110.97, 38.83, 234.18]"}
      hash[:data] # => "[209.04, 110.97, 38.83, 234.18]"
      
      require 'json'
      JSON[hash[:data]] # => [209.04, 110.97, 38.83, 234.18]
      

      数据看起来像是 JSON 编码的浮点数数组,因此请这样对待。

      综合起来:

      hash[:data] = JSON[hash[:data]]
      hash # => {:name=>"testname", :data=>[209.04, 110.97, 38.83, 234.18]}
      

      此时hash相当于:

      {name: "testname", data: [209.04, 110.97, 38.83, 234.18]} # => {:name=>"testname", :data=>[209.04, 110.97, 38.83, 234.18]}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-11
        • 2013-12-09
        • 1970-01-01
        • 2014-03-20
        • 2017-06-09
        • 2021-11-03
        • 2020-10-31
        • 2012-01-12
        相关资源
        最近更新 更多