I am writing a program that will reshuffle passengers on the bus. I want to record how many shuffles it takes to re-order the seating on the bus. Thought I had it, but I cannot change self.reshuffle_count
. How do I access @reshufffle_count
from the method reshuffle_seating
class MagicBus < Array
attr_writer :seating
def seating
@seating || []
end
def reshuffle_count
@reshuffle_count || 0
end
def reshuffle_seating
max_passengers = self.seating.max
popular_seat = self.seating.max
pop_seat_indx = self.seating.find_index(popular_seat)
reshuffle_num = 0
self.seating.rotate!(pop_seat_indx)
while popular_seat > 1 do
self.seating.each_with_index do |seat, index|
if index != 0
self.seating[index] = self.seating[index] +1
popular_seat = popular_seat -1
else
reshuffle_num = reshuffle_num +1
p reshuffle_num
end
end
end
self.seating.rotate!(pop_seat_indx*-1)
self.seating[pop_seat_indx] = popular_seat
self.reshuffle_count = reshuffle_num
end
end
class TestMagicBusSeating < MiniTest::Test
def test_reshuffle_seating_instance1
bus = MagicBus.new
bus.seating = [0,2,7,0]
bus.reshuffle_seating
assert_equal([2, 4, 1, 2], bus.seating)
assert_equal(5, bus.reshuffle_count)
end
end
Error Message is
Error:
TestMagicBusSeating#test_reshuffle_seating_instance1:
NoMethodError: undefined method `reshuffle_count=' for []:MagicBus
Did you mean? reshuffle_count
magic_bus.rb:99:in `reshuffle_seating'
magic_bus.rb:217:in `test_reshuffle_seating_instance1'
NoMethodError: undefined method `reshuffle_count='
That means you are missing a setter
. You have the getter defined def reshuffle_count
but no setter.
class MagicBus < Array
attr_writer :seating
def seating
@seating || []
end
def reshuffle_count=(value)
@reshuffle_count=value
end
def reshuffle_count
@reshuffle_count || 0
end
.....
Or as @tadman pointed out, attr_writer :resuffle_count