"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. 1 miles to km 1.60934 km 5 miles to km 8.04672 km 10 miles to km 16.09344 km 15 miles to km 24.14016 km 20 miles to km 32.18688 km 25 miles to km 40.2336 km 30 miles to km 48.28032 km 40 miles to km 64.37376 km 50 miles to km 80. This will provide you with the following sample outputs: convert_distance '10 miles' The imperial and US customary units for measuring the length are. # containing both a distance and a unit identifier.ĭist, unit = str.scan(/( )\s*(\S )/).flatten It means that one mile is nearly equivalent to 1.60934 km. # 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. |