1

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

1 Answer 1

1
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.

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

Comments

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.