0

I want the push elements of an API into my array if the condition for an attribute is true. So k_api_hash['awsaccounts'][i]['sandman'] will return true or false and, if the condition is true, I want to push the account number in to an array; (k_api_hash['awsaccounts'][i]['accountnumber']) will return an account number.

Code:

k_api_hash = JSON.parse(kens_api)
aws_account_size = k_api_hash["awsaccounts"].size
aws_account_array = []

i = 0
while i < aws_account_size
  if k_api_hash['awsaccounts'][i]['sandman'] == "true"
    aws_account_array.push(k_api_hash['awsaccounts'][i]['accountnumber'])
    i += 1
  else
    i += 1
  end
end

puts "Here are all the aws accounts"
puts aws_account_array.inspect

The problem is that it is returning null value, but successfully pushes the account numbers into the array if the if condition is taken out.

Output:

Here are all the aws accounts
[] 

2 Answers 2

1

The if is returning false every time because you are comparing "true" (String) with true (TrueClass) / false (FalseClass); consider the following code:

true == "true"
#=> false

false == "true"
#=> false

true != "true"
#=> true

To make it work simply remove == "true"1 from your if:

if k_api_hash['awsaccounts'][i]['sandman']

1 Remember that any expression in an if that returns true/false (or a truthy/falsey value for that matter) needs no further comparison.


Not related to the error, but your code could be optimized by using a different iterator and removing unnecessary variables; for example, the following code will yield the same output:

k_api_hash = JSON.parse(kens_api)

aws_account_array = k_api_hash["awsaccounts"].each_with_object([]) do |account, r|
  r << aws_account_array.push(account['accountnumber']) if account['sandman']
end

To understand better what is going on, take a look at Enumerable#each_with_object.

Sign up to request clarification or add additional context in comments.

Comments

0

I think this would do the job:

k_api_hash = JSON.parse(kens_api)
awsaccounts = k_api_hash['awsaccounts']
aws_account_array = awsaccounts.reduce([]) { |array, acc|
  array << acc['accountnumber'] if acc['sandman']
  array
}

If the API is returning string booleans like "true" or "false" you could do a hash like:

  bools = {true=>true, 'true'=>true}

and call it using what api returns as key inside the reduce

  array << acc['accountnumber'] if bools[acc['sandman']]

2 Comments

I don't think that bools hash is necessary, according to OP the API will return either true or false, so there is no need to check for "true" (or "false") .
You could leave a side note to give the option to OP, no harm in giving extra info. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.