简体   繁体   English

Ruby / Rails:每个do循环都来自另一个循环

[英]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. 我正在使用以下每个do循环从JSON文件中提取数据并使其在我的网站上可用。

<% 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. 但是,我要基于另一个JSON文件中的字段更改范围(0..5),范围始终是6的块,因此(0..5),(6..11) ,(12..17)等。

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. 这行不通,我希望能够从第一个JSON文件中提取z1和z2结果。

Is there a way that I can do this? 有办法可以做到吗? Is there something I'm missing? 有什么我想念的吗?

Below are examples of the JSON being used. 以下是正在使用的JSON的示例。

JSON 1 JSON 1

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

JSON 2 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. 您可以使用ruby已经内置的可枚举方法each_slice指定切片长度,它将将数组切成具有该长度的切片,然后将切片传递给块。

You'll probably need to convert the json into a hash, but that's easy, 您可能需要将json转换为哈希,但这很容易,

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

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

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