An API I’m using returns different content depending on circumstances.
Here’s a snippet of what the API might return:
pages = [
{
'id' => 100,
'content' => {
'score' => 100
},
},
{
'id' => 101,
'content' => {
'total' => 50
},
},
{
'id' => 102,
},
]
content
is optional, and can contain different items.
I would like to return a list of pages where the score
is more than 75.
So far this is as small as I can make it:
pages.select! do |page|
page['content']
end
pages.select! do |page|
page['content']['score']
end
pages.select! do |page|
page['content']['score'] > 75
end
If I was using JavaScript, I would do this:
pages.select(page => {
if (!page['content'] || !page['content']['score']) {
return false
}
return page['content']['score'] > 75
})
Or perhaps if I was using PHP, I would array_filter
in a similar way.
However, trying to do the same thing in Ruby throws this error:
LocalJumpError: unexpected return
I understand why you cannot do that. I just want to find a simple way to achieve this in Ruby.
Here’s my make-believe Ruby I want to magically work:
pages = pages.select do |page|
return unless page['content']
return unless page['content']['score']
page['content']['score'] > 75
end