ibpix
ibpix

Reputation: 319

How to check and return string or return false and exit if statement

Working in Rails 4.2 and Ruby 2.3.3

I'm dealing with an API that has an error fiend in certain circumstances but not in other circumstances. I would like to check to see if that error key exists and, if yes, downcase it and search for the existence of something. Like this where parsed is a hash:

# parsed could be either:
# {error: "Email does not exist"}
# or 
# {result: ... }

return true  if parsed.dig('error').downcase!.include?('email does not exist') # refactor

I can see dig returns nil in this case. Is there any way I can tell that if statement to exit if nil? Maybe force it to false and exit without adding a lot of ceremony code?

I know I could do something like this but it seems cumbersome:

unless parsed['error'].nil?
  return true  if parsed.dig('error').downcase!.include?('email does not exist') # refactor
end

Upvotes: 1

Views: 321

Answers (1)

anothermh
anothermh

Reputation: 10526

parsed.dig('error').to_s.downcase.include?('email does not exist')

to_s converts nil to ''. No need for downcase! because you don't need to mutate the original object and because it returns nil if no changes were made; just use downcase.

Note that your example uses symbolized keys and your code uses stringified keys, so it'll never match:

parsed = {error: "Email does not exist"} # key is symbolized
parsed.dig('error').to_s.downcase.include?('email does not exist') # key is stringified
=> false

parsed = {error: "Email does not exist"} # key is symbolized
parsed.dig(:error).to_s.downcase.include?('email does not exist') # key is symbolized
=> true

Since you're using Rails, you can make your life a little easier with indifferent access. This allows hash keys to be accessed by string or by symbol:

parsed.with_indifferent_access.dig('error').to_s.downcase.include?('email does not exist')
=> true
parsed.with_indifferent_access.dig(:error).to_s.downcase.include?('email does not exist')
=> true

Using this gives you some flexibility.

Upvotes: 1

Related Questions