سؤال

I'm curious as to why this is happening:

user_uid = user[:user_uid] || next_uid

can return nil, although I would think if the first value is nil, it executes the next_uid method. If i change || to ||=, then it returns the results of next_uid if user[:user_uid] is nil

So the question is, why does

user_uid = user[:user_uid] ||= next_uid

require the ||= operator while the following does not?

@terms_accepted = options[:terms_accepted] || false

relevant code:

    def insert(user)
      store_user(user)
    end

    def get(user_uid)
      #validations

      users[user_uid]
    end

    private

    def store_user(user)
      user_uid = user[:user_uid] || next_uid

      users[user_uid] = user

      return user_uid
    end

    def next_uid
      @memory[:user_uid] ||= 0
      "#{@memory[:user_uid] += 1}"
    end

test code in question:

it "stores users" do
  user = { 
    :user_uid => nil 
  }
  uid = subject.insert(user)

  assert_user_was_stored(uid)
end

def assert_user_was_stored(expected_uid)
  result = subject.get(expected_uid)

  assert_equal expected_uid, result[:user_uid]
end
هل كانت مفيدة؟

المحلول

You're facing this issue becuase you're not check value returned from store_user method, but user[:user_uid] value (exactly as @Neil Slater said). So, if you use ||, user[:user_uid] remains nil. But if you use ||=, user[:user_uid] is set to value returned by next_uid method.

نصائح أخرى

the problem was that i was assigning two values at once - user_uid and user[:user_uid] if it was unset. A better way is to make this two lines:

# first set the value of user[:user_uid] if it is nil
user[:user_uid] ||= next_uid 

# then set the value of the local variable
user_uid = user[:user_uid] 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top