arjun arjun - 3 months ago 16
Ruby Question

Rails extract data strange behaviour from Array of Array containing Hash

I have this response from an

{"Dates"=>[[{"DateString"=>"2016-09-01"}, {"DateString"=>"2016-09-02"}, {"DateString"=>"2016-09-03"}, {"DateString"=>"2016-09-04"}, {"DateString"=>"2016-09-05"}, {"DateString"=>"2016-09-06"}, {"DateString"=>"2016-09-07"}, {"DateString"=>"2016-09-08"}], [{"MinPrice"=>3669.0, "QuoteDateTime"=>"2016-09-01T12:49:10"}, {"MinPrice"=>3216.0, "QuoteDateTime"=>"2016-09-01T15:53:40"}, {"MinPrice"=>2668.0, "QuoteDateTime"=>"2016-09-01T13:48:21"}]], "Places"=>[{"PlaceId"=>42850, "...}


This is my code

<% @result["Dates"].each do |f| %>
<% Array.wrap(f).each do |seg| %>
<%= seg['DateString'] %> - <%= seg['MinPrice'] %>
<br>
<% end %>
<% end %>


This is like an Array of Array containing hashes but when I try to extract
DateString
and
MinPrice
together, I am getting a result like this

2016-09-01 -
2016-09-02 -
2016-09-03 -
2016-09-04 -
2016-09-05 -
2016-09-06 -
2016-09-07 -
2016-09-08 -
- 3669.0
- 3230.0
- 2809.0
- 2668.0
- 3216.0
- 2507.0
- 3216.0
- 2848.0
- 3216.0


What I am trying is rather this arrangement

2016-09-01 - 3669.0
2016-09-02 - 3230.0
2016-09-03 - 2809.0
2016-09-04 - 2668.0


i.e., Datestring and Minprice together

Where is the code not correct?




Also, strangely, if the code is rearranged like this

<%= seg['MinPrice'] %> - <%= seg['DateString'] %> <br>


It would still show up like this

- 2016-09-01
- 2016-09-02
- 2016-09-03
.
.
.
3669.0 -
3230.0 -
2809.0 -


Why is it like that?

Answer

Does this work for you?

<% @result["Dates"][0].zip(@result["Dates"][1]).each do |f,a| %>
  <%= "#{f['DateString']} - #{a['MinPrice']}" if f && a %>
  <br>
<% end %>

It's far from pretty, but it might be a good start.