# Dynamic loop in a hash

**URL:** <https://www.ruby-forum.com/t/dynamic-loop-in-a-hash/221905>\
**Category:** Rails\
**Created:** [August 3, 2012, 11:03pm UTC](https://www.ruby-forum.com/t/dynamic-loop-in-a-hash/221905 "2012-08-03T23:03:04Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![aris](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/258eb7/32.png) [@aris](https://www.ruby-forum.com/u/aris)\
**Post date:** [August 3, 2012, 11:03pm UTC](https://www.ruby-forum.com/t/dynamic-loop-in-a-hash/221905/1 "2012-08-03T23:03:04Z")

</div>

I’m trying to create a dynamic loop within the hash @data below and  
can’t really seem to figure it out. The array within the hash has to be  
dynamic i:e the day number has to be generated by a loop either while or  
until and the name of the product and number are dynamic as well. I’ll  
try to explain in the loop below

@numdeployed comes from a table in the db

i = 0  
until i == 12  
i.day.ago.to\_date =\> { :coder=\>@numdeployed, :imedidata=\>@numdeployed,  
:balance=\>@numdeployed, :CTMS=\>@numdeployed },  
i += 1  
end

Original Data Hash

@data = {  
1.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
2.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
3.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
4.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
5.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
6.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
7.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
8.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
9.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
10.day.ago.to\_date =\> { :coder=\>200, :imedidata=\>190, :balance=\>70,  
:CTMS=\>90 },  
11.day.ago.to\_date =\> { :coder=\>190, :imedidata=\>200,  
:balance=\>200, :CTMS=\>150 },  
12.day.ago.to\_date =\> { :coder=\>100, :imedidata=\>400,  
:balance=\>100, :CTMS=\>100 }

}

hope someone can help. Thanks

---

<div class="post-metadata">

**Author:** ![staypufd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecd19e/32.png) [@staypufd](https://www.ruby-forum.com/u/staypufd)\
**Post date:** [August 3, 2012, 11:14pm UTC](https://www.ruby-forum.com/t/dynamic-loop-in-a-hash/221905/2 "2012-08-03T23:14:48Z")

</div>

On 3 August 2012 22:03, Sam G. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> i.day.ago.to\_date =\> { :coder=\>@numdeployed, :imedidata=\>@numdeployed,  
> :balance=\>@numdeployed, :CTMS=\>@numdeployed },  
> i += 1  
> end
> 
> Original Data Hash
> 
> @data = {  
> 1.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
> :CTMS=\>40 },

How can you have a Date object as the key to a hash? Show us for an  
actual date what you want to see here.

---

<div class="post-metadata">

**Author:** ![staypufd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecd19e/32.png) [@staypufd](https://www.ruby-forum.com/u/staypufd)\
**Post date:** [August 4, 2012, 12:04am UTC](https://www.ruby-forum.com/t/dynamic-loop-in-a-hash/221905/3 "2012-08-04T00:04:29Z")

</div>

This should work:

items = 12.times.map { [i.day.ago.to\_date, { :coder=\>@numdeployed, :imedidata=\>@numdeployed, :balance=\>@numdeployed, :CTMS=\>@numdeployed }] }.flatten  
result = Hash[\*items]

Daniel

---

<div class="post-metadata">

**Author:** ![staypufd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecd19e/32.png) [@staypufd](https://www.ruby-forum.com/u/staypufd)\
**Post date:** [August 4, 2012, 12:11am UTC](https://www.ruby-forum.com/t/dynamic-loop-in-a-hash/221905/4 "2012-08-04T00:11:02Z")

</div>

Colin L. wrote in post #1071227:

> On 3 August 2012 22:03, Sam G. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:
> 
> > i.day.ago.to\_date =\> { :coder=\>@numdeployed, :imedidata=\>@numdeployed,  
> > :balance=\>@numdeployed, :CTMS=\>@numdeployed },  
> > i += 1  
> > end
> > 
> > Original Data Hash
> > 
> > @data = {  
> > 1.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
> > :CTMS=\>40 },
> 
> How can you have a Date object as the key to a hash? Show us for an  
> actual date what you want to see here.

the date object has to be there. That helps to build the javascript that  
creates the graphical timeline.

---

<div class="post-metadata">

**Author:** ![staypufd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecd19e/32.png) [@staypufd](https://www.ruby-forum.com/u/staypufd)\
**Post date:** [August 4, 2012, 12:11am UTC](https://www.ruby-forum.com/t/dynamic-loop-in-a-hash/221905/5 "2012-08-04T00:11:40Z")

</div>

Daniel M. wrote in post #1071237:

> This should work:
> 
> items = 12.times.map { [i.day.ago.to\_date, { :coder=\>@numdeployed,  
> :imedidata=\>@numdeployed,  
> :balance=\>@numdeployed, :CTMS=\>@numdeployed } ] }.flatten  
> result = Hash[\*items]
> 
> Daniel

Thanks Daniel, I will try this.

---

<div class="post-metadata">

**Author:** ![staypufd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecd19e/32.png) [@staypufd](https://www.ruby-forum.com/u/staypufd)\
**Post date:** [August 4, 2012, 3:24am UTC](https://www.ruby-forum.com/t/dynamic-loop-in-a-hash/221905/6 "2012-08-04T03:24:36Z")

</div>

Sam G. wrote in post #1071240:

> Colin L. wrote in post #1071227:
> 
> > On 3 August 2012 22:03, Sam G. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:
> > 
> > > i.day.ago.to\_date =\> { :coder=\>@numdeployed, :imedidata=\>@numdeployed,  
> > > :balance=\>@numdeployed, :CTMS=\>@numdeployed },  
> > > i += 1  
> > > end
> > > 
> > > Original Data Hash
> > > 
> > > @data = {  
> > > 1.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
> > > :CTMS=\>40 },
> > 
> > How can you have a Date object as the key to a hash? Show us for an  
> > actual date what you want to see here.
> 
> the date object has to be there. That helps to build the javascript that  
> creates the graphical timeline.

Daniel, I tried your suggestion but it did not work. I"m not sure if you  
can look at the actual plugin code. Maybe this will give you an idea of  
what I’m trying to do. Thanks again.

########################## original controller code. code I’m trying to  
replace with what you have written

@data = {  
1.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
2.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
3.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
4.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
5.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
6.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
7.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
8.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
9.day.ago.to\_date =\> { :coder=\>10, :imedidata=\>40, :balance=\>10,  
:CTMS=\>40 },  
10.day.ago.to\_date =\> { :coder=\>200, :imedidata=\>190, :balance=\>70,  
:CTMS=\>90 },  
11.day.ago.to\_date =\> { :coder=\>190, :imedidata=\>200,  
:balance=\>200, :CTMS=\>150 },  
12.day.ago.to\_date =\> { :coder=\>100, :imedidata=\>400,  
:balance=\>100, :CTMS=\>100 }  
}

################################ View code

\<%= inline\_annotated\_timeline @data, “900”, “300”, ‘div\_id\_to\_create’ %\>

####################### plugin code ######################

## Sample generated Javascript

# \<script type=“text/javascript”

src=“[http://www.google.com/jsapi](http://www.google.com/jsapi)”\>

# ".html\_safe end

private  
def ruby\_time\_to\_js\_date(date)  
“new Date(#{date.year}, #{date.month-1}, #{date.day})”  
end

def ruby\_time\_to\_js\_time(time)  
time = time.to\_time if !time.is\_a?(Time)  
if @time\_zone && time.respond\_to?(:in\_time\_zone)  
time = time.in\_time\_zone(@time\_zone)  
end  
“new Date(#{time.year}, #{time.month-1}, #{time.day}, #{time.hour},  
#{time.min})”  
end

def ruby\_hash\_to\_js\_hash(hash)  
hash.map{|key,val| “#{key}: #{val}”}  
end

def format\_options\_for\_javascript(options, daily\_graph=true)  
valid\_options = {}  
options.each do |k,v|  
valid\_options[k] = case v  
when String, Array then v.inspect #this turns ‘red’ into  
‘"red"’ for strings and %w[red blue] into ["red", "blue"] for  
arrays  
when Date,Time then (daily\_graph) ?  
ruby\_time\_to\_js\_date(v) : ruby\_time\_to\_js\_time(v)  
else v #leave bools and numbers as they are  
end  
end

```
# a hash containing annotations is passed into the ruby options 

```

hash, keyed as :annotations. this hash  
# doesn’t get sent to the javascript function - javascript takes the  
annotations as data points. the js  
# function does, however, require the boolean :displayAnnotations  
if (options[:annotations] && options[:annotations].any?)  
valid\_options[:displayAnnotations] = true  
end  
valid\_options.reject!{|k,v| k == :annotations || v == nil}

```
ruby_hash_to_js_hash valid_options

```

end

def is\_daily?(daily\_counts\_by\_type={})  
return true if (daily\_counts\_by\_type.keys.first.is\_a?(Date))  
return true if (daily\_counts\_by\_type.length \< 2)

```
sorted_keys = daily_counts_by_type.keys.sort
(sorted_keys[1] - sorted_keys[0]) > 2.hours

```

end

def google\_graph\_data(daily\_counts\_by\_type, daily\_graph, options)  
categories =   
num = 0  
html = “”  
# Offset used to keep track of nested annotations.  
index\_offset = 0

```
#set up columns and assign them each an index
if daily_graph
  html << "data.addColumn('date', 'Date'); \n"
else
  html << "data.addColumn('datetime', 'Date'); \n"
end
types( daily_counts_by_type ).each do |type|
  html<<"data.addColumn('number', '#{type.titleize}');\n"
  categories << type.to_sym

  if options[:annotations] && 

```

options[:annotations].keys.include?(type.to\_sym)  
html\<\<“data.addColumn(‘string’,  
‘#{type.titleize}\_annotation\_title’);\n”  
categories \<\< “#{type}\_annotation\_title”.to\_sym

```
    html<<"data.addColumn('string', 

```

‘#{type.titleize}\_annotation\_text’);\n"  
categories \<\< “#{type}\_annotation\_text”.to\_sym

```
    options[:annotations][type.to_sym].each do |date, array|
      if not daily_counts_by_type.key?(date)
        daily_counts_by_type[date] = {}
      end

      # We'll need additional date fields only if we have more than 

```

one annotation.  
index\_offset += (array.size-1)

```
      # Preserve multiple annotations.
      daily_counts_by_type[date]["#{type}_annotation_title".to_sym] 

```

= array  
end  
end  
end

```
#The script expects a constant telling it how many rows we're going 

```

to add  
html\<\<“data.addRows(#{(daily\_counts\_by\_type.size+index\_offset)});\n”

```
html<<add_data_points(daily_counts_by_type, categories, daily_graph)
html

```

end

# Converts this:

# { :Date1=\>{:type1=\>9, :type2=\>9},

# :Date2=\>{:type1=\>9, :type3=\>9} }

# into

# [‘type1’, ‘type2’, ‘type3’]

# We can’t just take the keys of the first item because not every date

has every category  
def types( daily\_counts\_by\_type )  
daily\_counts\_by\_type.values.inject({}){|a,b|a.merge(b)}.stringify\_keys.keys.sort  
end

def add\_data\_points(daily\_counts\_by\_type, categories, daily\_graph)  
html = “”  
total\_count = 0  
# Offset used to keep track of nested annotations.  
index\_offset = 0

```
#sort by date
daily_counts_by_type.sort{|a,b| a[0]<=>b[0]}.each_with_index do 

```

|obj, index|  
date, type\_and\_count = obj  
js\_date = (daily\_graph) ? ruby\_time\_to\_js\_date(date) :  
ruby\_time\_to\_js\_time(date)  
html\<\<“data.setValue(#{(index+index\_offset)}, 0, #{js\_date});\n”

```
  #now, on a particular date, go through columns
  categories.each_with_index do |category, idx2|
    value = type_and_count[category]
    if value && category.to_s.include?("_annotation_")
      first_iteration = true
      value.each do |v|
        if (!first_iteration)
          index_offset += 1
          html<<"data.setValue(#{(index+index_offset)}, 0, 

```

#{js\_date});\n"  
end  
html\<\<“data.setValue(#{(index+index\_offset)}, #{idx2+1},  
"#{v[0]}");\n” if v[0]  
# XXX: We assume the \_text index is right after the \_title  
index.  
html\<\<“data.setValue(#{(index+index\_offset)}, #{idx2+2},  
"#{v[1]}");\n” if v[1]  
first\_iteration = false  
end  
elsif value  
total\_count = total\_count + value.to\_i  
html\<\<“data.setValue(#{(index+index\_offset)}, #{idx2+1},  
#{value});\n” if value  
end  
end  
end  
(total\_count \> 0) ? html : “”  
end

end
