Monday, 28 April 2025
simple parcel alarm
Creating a simple parcel alarm in Ruby can be done using a combination of object-oriented programming and basic I/O. Below is an example implementation that simulates a parcel alarm system.
This example covers basic functionality such as setting an alarm for a parcel and checking if the parcel has been delivered. If not delivered within the set timeframe, it will trigger an alarm.
```ruby
class ParcelAlarm
attr_accessor :expected_delivery_time, :delivered, :alarm_triggered
def initialize(expected_delivery_time)
@expected_delivery_time = expected_delivery_time
@delivered = false
@alarm_triggered = false
end
def mark_as_delivered
@delivered = true
puts "Parcel has been delivered."
end
def check_delivery(current_time)
if @delivered
puts "The parcel has been delivered on time."
elsif current_time > @expected_delivery_time && !@alarm_triggered
trigger_alarm
else
puts "Parcel is still on its way. Expected delivery by #{@expected_delivery_time}."
end
end
private
def trigger_alarm
@alarm_triggered = true
puts "ALARM! The parcel was not delivered on time!"
end
end
# Example usage:
def main
puts "Enter the expected delivery time (in hours from now):"
hours = gets.chomp.to_i
expected_delivery_time = Time.now + (hours * 3600) # Convert hours to seconds
parcel_alarm = ParcelAlarm.new(expected_delivery_time)
# Simulate checking the delivery status
loop do
puts "Checking delivery status..."
parcel_alarm.check_delivery(Time.now)
# Allow the user to mark as delivered for testing
puts "Mark parcel as delivered? (y/n)"
response = gets.chomp.downcase
if response == 'y'
parcel_alarm.mark_as_delivered
break
end
sleep(5) # Check every 5 seconds
end
end
# Start the parcel alarm system
main
```
### Explanation:
1. **ParcelAlarm Class**: This class manages the expected delivery time, delivered status, and whether the alarm has been triggered.
- It has methods to mark the parcel as delivered and check the delivery status against the current time.
2. **Alarm Triggering**: When the current time exceeds the expected delivery time and the parcel has not been marked as delivered, the alarm is triggered.
3. **Main Method**:
- Prompts the user for the expected delivery time (in hours).
- Creates an instance of `ParcelAlarm`.
- Enters a loop to check the delivery status. The user has the option to mark the parcel as delivered, which breaks the loop.
4. **Looping & Sleep**: The status is checked every 5 seconds (to simulate a real-time monitoring system).
### Usage:
- Run the script, enter the expected delivery time, and then keep the program running. If you set a time far in the future and the parcel isn’t marked as delivered, you should see the alarm message printed.
Feel free to modify this code to implement additional features based on your requirements!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment