thefonso
thefonso

Reputation: 3390

how to get correct output from hash

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

Answers (2)

user904990
user904990

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

jboursiquot
jboursiquot

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

Related Questions