Reputation: 3390
I have a hash like so...
scores = {:b3=>1000, :c3=>-1000}
scores.each do |k,v|
if v = 1000
best_answer = k
elsif v = -1000
best_answer = k
end
end
p 'BEST_ANSWER'
p best_answer
return best_answer
I keep getting c3
best_answer SHOULD be b3
what am I doing wrong?
Upvotes: 0
Views: 43
Reputation:
you actually using assignment operator instead of equality one.
change =
to ==
:
if v == 1000
best_answer = k; break
elsif v == -1000
best_answer = k; break
end
also you would like to refactor your code.
best_answer = scores.key(-1000)
or
best_answer = scores.min.first
p best_answer
#=> :b3
Upvotes: 0
Reputation: 1271
First off, you need to change from assignment to comparison:
Not if v =
but rather if v ==
Second, when you reach your "best answer", you could just return the best_answer and forgo the rest of the iteration.
Upvotes: 1