简体   繁体   中英

Ruby/Rails: each do loop range from another loop

I'm using the following each do loop to pull in data from a JSON file and make it usable on my site.

<% data.games.ronedoneb.each do |s| %>

This is working great. What I'm wanting to do is to specify a range that will be used, like so:

<% data.games.ronedoneb[(0..5)].each do |s| %>

What I'm wanting to do however, is change the range (0..5) based on fields within another JSON file, the range will always be blocks of 6 so: (0..5), (6..11), (12..17) etc etc.

This is what I've tried to do is below:

<% data.games.ronedoneb[(<%= ss[:z1] %>..<%= ss[:z2] %>)].each do |s| %>

This doesn't work, I hoped that I'd be able to pull the z1 and z2 results from the first JSON file.

Is there a way that I can do this? Is there something I'm missing?

Below are examples of the JSON being used.

JSON 1

"Ar": "1",
"Br": "0",
"Round": "1",
"Game": "3",
"Date": "Thursday, 5 February 2015",
"Day": "1",
"z1": "12",
"z2": "17"

JSON 2

"Game": "1",
"AR": "9",
"Day": "1",
"GPMB": "351",
"DR": "2",
"CSB": "275",
"GPMR": "360",
"AB": "1",
"Round": "1",
"CSp10R": "60",
"GoldR": "13.2",
"DB": "2",
"CSR": "222",
"GoldB": "12.9",
"KDAR": "6.50",
"Blue": "23.7",
"CSat10B": "79",
"KB": "5",
"KDAB": "3.00",
"KR": "4",
"CSat10R": "76"

You can't use <%= in the place you did. Please try something like:

<% data.games.ronedoneb[(ss[:z1].to_i..ss[:z2].to_i)].each do |s| %>

You can use ruby's already built in enumerable method each_slice you specify the slice length and it will cut the array into slices with that length, then pass the slices to the block.

You'll probably need to convert the json into a hash, but that's easy,

data.games.ronedoneb.each_slice(5) do |slice|
  slice.each do |item|
    #process here
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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