避免型別確認
Bad:
Bad:
def travel_to_texas(vehicle)
if vehicle.is_a?(Bicycle)
vehicle.pedal(@current_location, Location.new(‘texas’))
elsif vehicle.is_a?(Car)
vehicle.drive(@current_location, Location.new(‘texas’))
end
end
Good:
def travel_to_texas(vehicle)
vehicle.move(@current_location, Location.new(‘texas’))
end
### 再避免型別確認
工具 [contracts.ruby](https://github.com/egonSchiele/contracts.ruby
)
**Bad:**
“`ruby
def combine(val1, val2)
if (val1.is_a?(Numeric) && val2.is_a?(Numeric)) ||
(val1.is_a?(String) && val2.is_a?(String))
return val1 + val2
end
raise ‘Must be of type String or Numeric’
end
Good:
def combine(val1, val2)
val1 + val2
end