简体   繁体   English

哈希在Ruby on Rails中的动态循环

[英]dynamic loop in a hash Ruby on Rails

I'm trying to create a dynamic loop within the hash @data below and can't really seem to figure it out. 我正在尝试在下面的哈希@data中创建一个动态循环,似乎无法弄清楚。 I'm creating an annotatedtimeline-for-rails using the google api from here https://github.com/mcommons/annotatedtimeline-for-rails . 我正在从这里https://github.com/mcommons/annotatedtimeline-for-rails使用google api创建一个带注释的timeline-for-rails。

The array within the hash @data has to be dynamic i:e the day number has to be generated by a loop and the name of the product and number are dynamic as well. 哈希@data中的数组必须是动态的,即必须通过循环来生成日期编号,并且产品名称和编号也是动态的。 I'll try to give an example in the loop below 我将在下面的循环中尝试给出一个例子

@numdeployed is a number and comes from a table in the db i should be generated by the loop @numdeployed是一个数字,来自数据库中的一个表,我应该由循环生成

@data{
    begin loop
    i.day.ago.to_date => { :foo=>@numdeployed, :bar=>@numdeployed, :barbaz=>@numdeployed, :foobar=>@numdeployed },
    end loop
}

The Original Data Hash looks like this 原始数据哈希看起来像这样

@data = {
    1.day.ago.to_date => { :foo=>10, :bar=>40, :barbaz=>10, :foobar=>40 },
    2.day.ago.to_date => { :foo=>10, :bar=>40, :barbaz=>10,:foobar=>40 },
    3.day.ago.to_date => { :foo=>10, :bar=>40, :barbaz=>10,:foobar=>40 },
    4.day.ago.to_date => { :foo=>10, :bar=>40, :barbaz=>10,:foobar=>40 },
    5.day.ago.to_date => { :foo=>10, :bar=>40, :barbaz=>10,:foobar=>40 }
}

hope someone can help. 希望有人可以帮忙。 Thanks 谢谢

Are you looking for something like this? 您是否正在寻找这样的东西?

@data = Hash[
    n.times.map do |i|
        [ (i + 1).day.ago.to_date,  { :foo => 10, :bar => 40, :barbaz => 10, :foobar => 40 } ]
    end
]

The n is however many pairs you want in your @data . 但是,您要在@data n对。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM