【问题标题】:How do I format this hash?如何格式化此哈希?
【发布时间】:2012-01-01 03:17:44
【问题描述】:

我有一个 UUID,每个 UUID 都有三个独特的属性。我想存储所有这些。我知道我需要在哈希中添加一个哈希,但我在执行此操作时遇到了麻烦。

它在循环中创建它们,并且对于每次迭代,我都需要将其附加/添加到哈希中,所以我也不知道该怎么做。

19ee480015a2012f0aeb64ce8f2f69f4:
status: complete
name: SaveComment
pct_complete: 100 

083732301597012f0aea64ce8f2f69f4:
status: working
name: SaveComment
pct_complete: 35 

bf40ca301596012f0ae864ce8f2f69f4:
status: complete
name: SaveComment
pct_complete: 100 

这是它要进入的代码:

get '/percentcomplete' do
  progress = {}
  Resque::Status.status_ids.each do |uuid|
    active_status = Resque::Status.get(uuid)

    #update hash each loop here with name, status, pct_complete, and uuid
  end
end

【问题讨论】:

  • 那么,问题是什么?
  • 我如何格式化哈希,就像我不知道里面有什么。我能想到的只是一个散列是用于字典之类的东西..在层次结构的同一级别上。我也不知道如何将每个新组添加到循环中的哈希中,以便它保留 {{uuid,this,that}{uuid,this,that}}
  • 澄清:我不知道如何告诉它每个“块”都是它自己的哈希部分。我不希望只是将它们全部串在一起,例如:uuid,this,that,uuid,this,that。我希望它们被分组,但仍然在同一个哈希中。此外,我不知道如何附加哈希..我假设合并,但我不知道这是否是最好的方法。我尝试连接一个数组,但它没有保留 groupins [[a,b],[a,b]]。我想最终使用散列,因为它要使用 json,但我什至不知道如何让它与数组一起使用
  • 为什么需要哈希?你可以使用带有一些属性的普通 ol' Ruby 对象吗?
  • 编辑:我在上面添加了我正在使用的代码,这有助于更有意义

标签: ruby-on-rails ruby hash


【解决方案1】:

假设我们可以从 active_status 对象中获取名称、状态、pct_complete,

get '/percentcomplete' do
  progress = {}
  Resque::Status.status_ids.each do |uuid|
    active_status = Resque::Status.get(uuid)

    #update hash each loop here with name, status, pct_complete, and uuid
    progress[uuid.to_s] = {:name => active_status.name, 
            :status => active_status.status, 
            :ptc_complete => active_status.ptc_complete}
  end
end

【讨论】:

  • 这比我想象的要容易......所以真的没有添加运算符吗?您只需用新键覆盖变量并添加它?
  • 有一个 store 方法,我们可以将 key 和 value 作为参数传递给它。您可以查看ruby-doc.org/core-1.9.3/Hash.html 了解更多详情。
猜你喜欢
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多