Reputation: 147
I have problem with searching for specific objects in array in ruby.
I've made a request to https://jsonplaceholder.typicode.com/todos
from where I get result JSON. I am trying to convert it to array of objects and then search for occurrences (I know that I can make a request with parameters and it will resolve my problems, but I do not have access to the backend).
I was trying to print objects in array containing some (specific) value in a termial and to get boolean value saying whether the string is present in array or not (I was also trying to find answer to my question on stack (this seems be the closest to my problem Ruby find and return objects in an array based on an attribute but didn't help me much).
client = HTTPClient.new
method = 'GET'
url = URI.parse 'https://jsonplaceholder.typicode.com/todos'
res = client.request method, url
dd = JSON.parse(res.body)
puts dd.select { |word| word.completed == false }
puts dd.include?('temporibus atque distinctio omnis eius impedit tempore molestias pariatur')
Actual results:
no result at all for select
and false
returned from include?
Expected result:
select
should put to terminal objects with completed
equal false
;
and include?
should return true
if value provided as parameter is present in the array
Upvotes: 3
Views: 1704
Reputation: 6555
Here's working code snippet:
require 'httpclient'
require 'json'
client = HTTPClient.new
method = 'GET'
url = URI.parse 'https://jsonplaceholder.typicode.com/todos'
res = client.request method, url
dd = JSON.parse(res.body)
# Use word['completed'] instead of word.completed here:
puts dd.select { |word| !word['completed'] }
# Use 'any?' array (Enumerable) method to check
# if any member of the array satisfies given condition:
puts dd.any? { |word| word['title'] == 'temporibus atque distinctio omnis eius impedit tempore molestias pariatur' }
Documentation for #any?
could be found here: https://apidock.com/ruby/Enumerable/any%3F
Upvotes: 2