Q.Super Q.Super - 16 days ago 6
Ruby Question

How can I change the value in each method?

From this code,I want to the last line:

puts computer_number
return 3.

But now it`s 5.

how can I do that?

def find_at_risk_square(square, computer_number)
WIN.each do |n|
array = []
n.each do |k|
array << square[k]
end
if array.count("X") == 2
computer_number = array.index(" ") + 1
end
end
end

WIN = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[3, 5, 7]].freeze

square = {1=>"X",2=>"X",3=>" ",4=>" ",5=>" ",6=>" "}
computer_number = "5"
find_at_risk_square(square, computer_number)
puts computer_number

Answer

You can change value in .each loop. You can't return a value from a method like that.

When you do computer_number = array.index(" ") + 1 in your method, you're assigning to a method-local variable. This will not affect outside world, be it in .each method or not.

Comments