0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyクラス作成

0
Posted at
ruby
class Car
  attr_reader :speed
  def initialize(speed)
    raise ArgumentError, 'speed < 0' if speed < 0
    @speed = speed
  end

  def time(distance)
    raise ArgumentError, 'distance < 0' if distance < 0
    return nil if @speed.zero?
    distance.to_f / @speed
  end
end

car = Car.new(50)
p car
p car.speed
p car.time(100) # => 2.0

car = Car.new(0)
p car.time(100) # => nil

begin
  Car.new(-1)
rescue ArgumentError => ex
  p ex
end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?