koushiskool
koushiskool

Reputation: 25

Conditional Boolean If statement syntax in ruby

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
[] 

Upvotes: 0

Views: 2776

Answers (2)

Cassiano
Cassiano

Reputation: 15

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']]

Upvotes: 0

Gerry
Gerry

Reputation: 10507

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.

Upvotes: 1

Related Questions