![]() ![]() ![]() "yards") simply by adding a new clause with the appropriate conversion ratio to the case statement. It's also easily expandable for other units of distance (e.g. This type of method isn't necessarily the simplest way to get the job done, but it certainly prevents you from having to define different methods for "km", "kilometers", "klicks", and so forth. This will provide you with the following sample outputs: convert_distance '10 miles' A kilometer, or kilometre, is a unit of length equal to 1,000 meters, or about 0.621 miles. It is commonly used to measure the distance between places in the United States and United Kingdom. A mile is a unit of distance equal to 5,280 feet or exactly 1.609344 kilometers. # containing both a distance and a unit identifier.ĭist, unit = str.scan(/( )\s*(\S )/).flatten How far is 1,000 miles in kilometers 1,000 mi to km conversion. # Make your method more flexible by accepting a string # Use constants for your conversion ratios. Here is an example where a single method takes a string as input, and returns an appropriate floating-point value for predefined units such as kilometers or miles while remaining flexible about the way the distance units are expressed. Sometimes it's useful to be less rigorous about how one expresses units of measurement while still being strict about the way the conversions are performed. A lot depends one what sort of input you expect from the caller, and what sort of result you want to pass back as your return values. There are lots of ways to solve this problem. ![]()
0 Comments
Leave a Reply. |