문제

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