Where is the best place to add methods to the Integer class in Rails?

前端 未结 7 2195
死守一世寂寞
死守一世寂寞 2021-02-10 05:56

Where is the best place to add a method to the integer class in Rails? I\'d like to add a to_meters and to_miles methods.

7条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-10 06:49

    Normally (and logically), integers can't be converted to miles or to meters. It sounds like you may want to create a new class like "Feet" or "inches" that is initialized with an integer, then contains methods like size_in_miles or size_in_meters. For convenience those methods could return decimal or float types, but you might also want to write a miles class or a meters class.

    As an alternate method, you might want to create a static method in your new class that would have a signature like this:

    Float feetToMiles(integer I)

    that you would call

    miles = Feet.feetToMiles(5280);

    and get miles = 1.0

提交回复
热议问题