I'm trying to figure out how to use define_method (or any other method) to generate array names as my method loops through an array and converts each hash element to JSON. Right now, my data is a series of hash arrays just dumped into a file, not contained in any larger array.
data_arrays = [{"key1":"value1"}, {"key2":"value2"}]
[{"key3":"value3"}, ("key4":"value4")]
[{"key5":"value5"}, ("key6":"value6")]
The code I was trying to work with is something like the following. Basically, I want each hash array to be converted into JSON and be assigned a new name, like json_array_1, jason_array_2, etc.
data_arrays.each do |element|
for (i = 0; i < data_array.length; i+=1) do
define_method("json_array_#{i}") do
json_array_[i] = element.to_json
end
end
end
I'm aware this line: for (i = 0; i < data_array.length; i+=1) do is not really Ruby or good code at all. But I needed a way to iterate through the loop while also making the variable "i" available to be inserted in the json_array names. Can anyone give me any pointers for getting this code to work? I'm probably overthinking things and making this harder than it actually is.
data_arrays.each_with_index do |element, i|(2) To call a method dynamically usesend("json_array_#{i}=", element.to_json)data_arrayshas several errors. See how I defined it in my answer.