I want to loop over JSON objects and check for a condition in a ruby function. I have 2 classes:
- Class
A - Class
B
Class A has a function that reads the JSON file.
This function returns an array of hash objects representing the data:
def self.data
path = 'data/songs.json'
file = File.read(path)
JSON.parse(file)
end
I want to use this method in class B to access the songs.json objects and check if a certain condition is true.
Here is the code for class B:
def mention_count
count = 0
array= []
array.push(Song.data)
array.each do |i|
if(@name === i[:name])
count +=1;
end
end
end
Th JSON file has a key called name, and I am checking if it is identical to the class B variable name. If true the count variable is increased and returned.
The JSON file is an array of JSON object and it looks like this
[
{
"Name": "Bad",
"Artist": "Michael Jackson",
"Record": 825,
},
{
"Name": "Thriller",
"Artist": "Michael Jackson",
"Record": 846,
}]
I am not getting the expected result. The array.push(Song.data) is only adding the first object of the JSON file and not the whole JSON file.
How do I call the method Song.data in class B and loop over the JSON objects?