This should be simple, but it's not I'm trying to generate a json with a loop inside it. Something like this:
all_urls = ["example.com/homepage", "example.com/another", "example.com"]
hash = {
"type":"URLS",
"Params":{
"rules":{
"condition":"AND",
"rules":[
begin
all_urls.each do |url|
{
"condition":"AND",
"rules":[
{
"value":[
"data",
"^https{0,1}:\\/\\/#{url}\\/{0,1}$"
]
},
{
"id":"@timestamp.age",
}
]
}
end
end
]
}
}
}
I want to get:
{
"type":"URLS",
"Params":{
"rules":{
"condition":"AND",
"rules":[
{
"condition":"AND",
"rules":[
{
"value":[
"data",
"^https{0,1}:\\/\\/example.com/homepage\\/{0,1}$"
]
},
{
"id":"@timestamp.age",
}
]
},
{
"condition":"AND",
"rules":[
{
"value":[
"data",
"^https{0,1}:\\/\\/example.com/another\\/{0,1}$"
]
},
{
"id":"@timestamp.age",
}
]
},
{
"condition":"AND",
"rules":[
{
"value":[
"data",
"^https{0,1}:\\/\\/example.com\\/{0,1}$"
]
},
{
"id":"@timestamp.age",
}
]
}
]
}
}
}
Tried using map, tried many things. Just either getting errors or getting an array thrown back to me.
EDIT: I'm going to provide the exact json structure I need to produce to be clearer.
UPDATE
Using Damian's suggestion, I am very close to getting this to work, but I only manage return the last result in the array. The first two get overwritten with the merge! probably? See below:
a = ["example.com/homepage", "example.com/another", "example.com"]
hash = {
"type":"condition",
"Params":{
"rules":{
"condition":"AND",
"rules":
(
a.inject(Hash.new) do |hash_container, element|
hash_container.merge!({
"condition":"AND",
"rules":[
{
"value":[
"^https{0,1}:\\/\\/#{element}\\/{0,1}$"
]
},
]
})
end
)
}
}
}
I'm getting:
=> {:type=>"condition", :Params=>{:rules=>{:condition=>"AND", :rules=>{:condition=>"AND", :rules=>[{:value=>["^https{0,1}:\\/\\/example.com\\/{0,1}$"]}]}}}}
UPDATE 3
It seems my main mistake was to assume that "rules" in my call was always an array, while in fact, it was sometimes an array and sometimes an object. Hence my confusion.
Both of the answers below are good solution and I ended up using Damian's inject of a hash to generate a hash within a loop, which was key to making it work.
What I ended up doing was creating that "Damian" array, then using #Unshift to prepend more objects to that array, and finally add that array within my call.
#dropin your example. Using that drop the first index from the array it returns, thus your example would only ever return["example.com"]#drop(1)will return ["example.com/another", "example.com"], leaving off "example.com/homepage" (so it won't ever make it into the loop). I'm working on an answer for you, but can I ask why not just callall_urls.each? are you purposefully wanting to drop the 1st elem?