-1

I am trying to build a console elevator simulator in OOP. I declared three attributes: currentFloor, minFloor and maxFloor with attr_accessor.

In currentFloor reader method, how can I check if the value is greater than maxFloor or lower than minFloor?

sawa
  • 165,429
  • 45
  • 277
  • 381

2 Answers2

1

As per your given requirement I have a solution that would help you.

You can define this way

class Elevator
  attr_accessor :current_floor, :min_floor, :max_floor

  def initialize(current_floor, min_floor, max_floor)
    @current_floor = current_floor
    @min_floor = min_floor
    @max_floor = max_floor
  end

end

Now you can assign the values to the all three attr_accessor

elevator = Elevator.new(100,150,500)

and now check get the values of the attr_accessor and also you check the condition whatever you want

if elevator.current_floor > elevator.max_floor
  // perform operation here
else
  // perform operation here
end

If you still have any query please let me know.

Sonu Singh
  • 305
  • 1
  • 10
0

refer What is attr_accessor in Ruby? for the different of the:

attr_accessor: define default getter and setter

attr_reader: define default getter

attr_writer: define default setter

depends on what you need, you should customise the getter or setter, In your example, if you want to customise your reader method:

class Elevator
  attr_writer :currentFloor
  def currentFloor
    if some_condition_check
      raise error
    end
    currentFloor
  end
end

But more often, you should customise your setter instead of getter, in which case:

class Elevator
  attr_reader :currentFloor
  def currentFloor=(current)
    if some_condition_check
      raise error
    end
    @currentFloor = current
  end
end
Community
  • 1
  • 1
Alba Hoo
  • 154
  • 8