Richlewis
Richlewis

Reputation: 15384

If/else returning the wrong value in Ruby

This seems somewhat simple but I can't seem to get this working correctly. I have a method with a simple if/else statement based upon a ENV

def auth_credentials
  if ENV['ENVIRONMENT'] == 'testenv1' || 'testenv2' || 'testenv3'
    { key: 'key1', secret: 'secret1' }
  elsif ENV['ENVIRONMENT'] == "testenv4"
    { key: 'key2', secret: 'secret2' }
  else
    raise 'Unable to set key/secret'
  end
end

So in my console I type ENV['ENVIRONMENT'] and I get testenv4 returned. However when I then try to get the relevant key

auth_credentials[:key]

I get key1 returned and not key2 as expected..

Any reason for this ? Have U done something ridiculously silly?

Upvotes: 0

Views: 85

Answers (2)

Dave Newton
Dave Newton

Reputation: 160301

Each compare needs to be separate, e.g.,

if (ENV['ENVIRONMENT'] == 'testenv1') || (ENV['ENVIRONMENT'] == 'testenv2') || (ENV['ENVIRONMENT'] == 'testenv3')

You probably want to use a case, though, e.g.,

case ENV['ENVIRONMENT']
when 'testenv1', 'testenv2', 'testenv3'
  # Do this
else
  # Do that
end

(Or Marek's include idea.)

I favor a further step; regactoring the logic into communicative methods, e.g.,

if test_environment?
  # Do this
elsif super_secrect_test_environment?
  # Do that
else
  # Do the other thing
end

Upvotes: 3

Marek Lipka
Marek Lipka

Reputation: 51181

This line:

ENV['ENVIRONMENT'] == 'testenv1' || 'testenv2' || 'testenv3'

is equivalent to:

(ENV['ENVIRONMENT'] == 'testenv1') || 'testenv2' || 'testenv3'

so it always returns true or 'testenv2', which are both truthy.

Instead, you should have:

if %w(testenv1 testenv2 testenv3).include? ENV['ENVIRONMENT']

Upvotes: 6

Related Questions