3

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

ray
  • 5,454
  • 1
  • 18
  • 40
Jacck Mark
  • 127
  • 1
  • 10
  • In your typicode link all of the `title` entries are missing the comma at the end of the line `{` `"UserId": 1,` `"Id": 1,` `"Title": "selected either the"` <- no comma `"Completed" false` `}` This will be cause an error if it is in the real data also. EDIT: Also missing commas between each object. – Tom Jan 08 '19 at 13:31
  • I don't see a problem (maybe i am missing something) but when i try to grab the response this looks perfectly fine and also when i go to given link chrome is showing me regular JSONs, looking like that: [ { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false },....] – Jacck Mark Jan 08 '19 at 13:44
  • oh man, my bad. I had translated the page without thinking and it messed up the formatting. :facepalm: – Tom Jan 08 '19 at 13:55

1 Answers1

2

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

EugZol
  • 6,476
  • 22
  • 41