-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathunit.rb
More file actions
1787 lines (1584 loc) · 64.5 KB
/
unit.rb
File metadata and controls
1787 lines (1584 loc) · 64.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
require "date"
module RubyUnits
# Copyright 2006-2025
# @author Kevin C. Olbrich, Ph.D.
# @see https://github.com/olbrich/ruby-units
#
# @note The accuracy of unit conversions depends on the precision of the conversion factor.
# If you have more accurate estimates for particular conversion factors, please send them
# to me and I will incorporate them into the next release. It is also incumbent on the end-user
# to ensure that the accuracy of any conversions is sufficient for their intended application.
#
# While there are a large number of unit specified in the base package,
# there are also a large number of units that are not included.
# This package covers nearly all SI, Imperial, and units commonly used
# in the United States. If your favorite units are not listed here, file an issue on GitHub.
#
# To add or override a unit definition, add a code block like this..
# @example Define a new unit
# RubyUnits::Unit.define("foobar") do |unit|
# unit.aliases = %w{foo fb foo-bar}
# unit.definition = RubyUnits::Unit.new("1 baz")
# end
#
class Unit < ::Numeric
class << self
# return a list of all defined units
# @return [Hash{Symbol=>RubyUnits::Units::Definition}]
attr_accessor :definitions
# @return [Hash{Symbol => String}] the list of units and their prefixes
attr_accessor :prefix_values
# @return [Hash{Symbol => String}]
attr_accessor :prefix_map
# @return [Hash{Symbol => String}]
attr_accessor :unit_map
# @return [Hash{Symbol => String}]
attr_accessor :unit_values
# @return [Hash{Integer => Symbol}]
attr_reader :kinds
end
self.definitions = {}
self.prefix_values = {}
self.prefix_map = {}
self.unit_map = {}
self.unit_values = {}
@unit_regex = nil
@unit_match_regex = nil
UNITY = "<1>"
UNITY_ARRAY = [UNITY].freeze
SIGN_REGEX = /(?:[+-])?/.freeze # +, -, or nothing
# regex for matching an integer number but not a fraction
INTEGER_DIGITS_REGEX = %r{(?<!/)\d+(?!/)}.freeze # 1, 2, 3, but not 1/2 or -1
INTEGER_REGEX = /(#{SIGN_REGEX}#{INTEGER_DIGITS_REGEX})/.freeze # -1, 1, +1, but not 1/2
UNSIGNED_INTEGER_REGEX = /((?<!-)#{INTEGER_DIGITS_REGEX})/.freeze # 1, 2, 3, but not -1
DIGITS_REGEX = /\d+/.freeze # 0, 1, 2, 3
DECIMAL_REGEX = /\d*[.]?#{DIGITS_REGEX}/.freeze # 1, 0.1, .1
# Rational number, including improper fractions: 1 2/3, -1 2/3, 5/3, etc.
RATIONAL_NUMBER = %r{\(?(?:(?<proper>#{SIGN_REGEX}#{DECIMAL_REGEX})[ -])?(?<numerator>#{SIGN_REGEX}#{DECIMAL_REGEX})/(?<denominator>#{SIGN_REGEX}#{DECIMAL_REGEX})\)?}.freeze # 1 2/3, -1 2/3, 5/3, 1-2/3, (1/2) etc.
# Scientific notation: 1, -1, +1, 1.2, +1.2, -1.2, 123.4E5, +123.4e5,
# -123.4E+5, -123.4e-5, etc.
SCI_NUMBER = /([+-]?\d*[.]?\d+(?:[Ee][+-]?\d+(?![.]))?)/.freeze
# ideally we would like to generate this regex from the alias for a 'feet'
# and 'inches', but they aren't defined at the point in the code where we
# need this regex.
FEET_INCH_UNITS_REGEX = /(?:'|ft|feet)\s*(?<inches>#{RATIONAL_NUMBER}|#{SCI_NUMBER})\s*(?:"|in|inch(?:es)?)/.freeze
FEET_INCH_REGEX = /(?<feet>#{INTEGER_REGEX})\s*#{FEET_INCH_UNITS_REGEX}/.freeze
# ideally we would like to generate this regex from the alias for a 'pound'
# and 'ounce', but they aren't defined at the point in the code where we
# need this regex.
LBS_OZ_UNIT_REGEX = /(?:#|lbs?|pounds?|pound-mass)+[\s,]*(?<oz>#{RATIONAL_NUMBER}|#{UNSIGNED_INTEGER_REGEX})\s*(?:ozs?|ounces?)/.freeze
LBS_OZ_REGEX = /(?<pounds>#{INTEGER_REGEX})\s*#{LBS_OZ_UNIT_REGEX}/.freeze
# ideally we would like to generate this regex from the alias for a 'stone'
# and 'pound', but they aren't defined at the point in the code where we
# need this regex. also note that the plural of 'stone' is still 'stone',
# but we accept 'stones' anyway.
STONE_LB_UNIT_REGEX = /(?:sts?|stones?)+[\s,]*(?<pounds>#{RATIONAL_NUMBER}|#{UNSIGNED_INTEGER_REGEX})\s*(?:#|lbs?|pounds?|pound-mass)*/.freeze
STONE_LB_REGEX = /(?<stone>#{INTEGER_REGEX})\s*#{STONE_LB_UNIT_REGEX}/.freeze
# Time formats: 12:34:56,78, (hh:mm:ss,msec) etc.
TIME_REGEX = /(?<hour>\d+):(?<min>\d+):?(?:(?<sec>\d+))?(?:[.](?<msec>\d+))?/.freeze
# Complex numbers: 1+2i, 1.0+2.0i, -1-1i, etc.
COMPLEX_NUMBER = /(?<real>#{SCI_NUMBER})?(?<imaginary>#{SCI_NUMBER})i\b/.freeze
# Any Complex, Rational, or scientific number
ANY_NUMBER = /(#{COMPLEX_NUMBER}|#{RATIONAL_NUMBER}|#{SCI_NUMBER})/.freeze
ANY_NUMBER_REGEX = /(?:#{ANY_NUMBER})?\s?([^-\d.].*)?/.freeze
NUMBER_REGEX = /(?<scalar>#{SCI_NUMBER}*)\s*(?<unit>.+)?/.freeze # a number followed by a unit
UNIT_STRING_REGEX = %r{#{SCI_NUMBER}*\s*([^/]*)/*(.+)*}.freeze
TOP_REGEX = /([^ *]+)(?:\^|\*\*)([\d-]+)/.freeze
BOTTOM_REGEX = /([^* ]+)(?:\^|\*\*)(\d+)/.freeze
NUMBER_UNIT_REGEX = /#{SCI_NUMBER}?(.*)/.freeze
COMPLEX_REGEX = /#{COMPLEX_NUMBER}\s?(?<unit>.+)?/.freeze
RATIONAL_REGEX = /#{RATIONAL_NUMBER}\s?(?<unit>.+)?/.freeze
KELVIN = ["<kelvin>"].freeze
FAHRENHEIT = ["<fahrenheit>"].freeze
RANKINE = ["<rankine>"].freeze
CELSIUS = ["<celsius>"].freeze
@temp_regex = nil
SIGNATURE_VECTOR = %i[
length
time
temperature
mass
current
substance
luminosity
currency
information
angle
].freeze
@kinds = {
-312_078 => :elastance,
-312_058 => :resistance,
-312_038 => :inductance,
-152_040 => :magnetism,
-152_038 => :magnetism,
-152_058 => :potential,
-7997 => :specific_volume,
-79 => :snap,
-59 => :jolt,
-39 => :acceleration,
-38 => :radiation,
-20 => :frequency,
-19 => :speed,
-18 => :viscosity,
-17 => :volumetric_flow,
-1 => :wavenumber,
0 => :unitless,
1 => :length,
2 => :area,
3 => :volume,
20 => :time,
400 => :temperature,
7941 => :yank,
7942 => :power,
7959 => :pressure,
7962 => :energy,
7979 => :viscosity,
7961 => :force,
7981 => :momentum,
7982 => :angular_momentum,
7997 => :density,
7998 => :area_density,
8000 => :mass,
152_020 => :radiation_exposure,
159_999 => :magnetism,
160_000 => :current,
160_020 => :charge,
312_058 => :conductance,
312_078 => :capacitance,
3_199_980 => :activity,
3_199_997 => :molar_concentration,
3_200_000 => :substance,
63_999_998 => :illuminance,
64_000_000 => :luminous_power,
1_280_000_000 => :currency,
25_600_000_000 => :information,
511_999_999_980 => :angular_velocity,
512_000_000_000 => :angle
}.freeze
# Class Methods
# Callback triggered when a subclass is created. This properly sets up the internal variables, and copies
# definitions from the parent class.
#
# @param [Class] subclass
def self.inherited(subclass)
super
subclass.definitions = definitions.dup
subclass.instance_variable_set(:@kinds, @kinds.dup)
subclass.setup
end
# setup internal arrays and hashes
# @return [Boolean]
def self.setup
clear_cache
self.prefix_values = {}
self.prefix_map = {}
self.unit_map = {}
self.unit_values = {}
@unit_regex = nil
@unit_match_regex = nil
@prefix_regex = nil
definitions.each_value do |definition|
use_definition(definition)
end
new(1)
true
end
# determine if a unit is already defined
# @param [String] unit
# @return [Boolean]
def self.defined?(unit)
definitions.values.any? { _1.aliases.include?(unit) }
end
# return the unit definition for a unit
# @param unit_name [String]
# @return [RubyUnits::Unit::Definition, nil]
def self.definition(unit_name)
unit = unit_name =~ /^<.+>$/ ? unit_name : "<#{unit_name}>"
definitions[unit]
end
# @param [RubyUnits::Unit::Definition, String] unit_definition
# @param [Proc] block
# @return [RubyUnits::Unit::Definition]
# @raise [ArgumentError] when passed a non-string if using the block form
# Unpack a unit definition and add it to the array of defined units
#
# @example Block form
# RubyUnits::Unit.define('foobar') do |foobar|
# foobar.definition = RubyUnits::Unit.new("1 baz")
# end
#
# @example RubyUnits::Unit::Definition form
# unit_definition = RubyUnits::Unit::Definition.new("foobar") {|foobar| foobar.definition = RubyUnits::Unit.new("1 baz")}
# RubyUnits::Unit.define(unit_definition)
def self.define(unit_definition, &block)
if block_given?
raise ArgumentError, "When using the block form of RubyUnits::Unit.define, pass the name of the unit" unless unit_definition.is_a?(String)
unit_definition = RubyUnits::Unit::Definition.new(unit_definition, &block)
end
definitions[unit_definition.name] = unit_definition
use_definition(unit_definition)
unit_definition
end
# Get the definition for a unit and allow it to be redefined
#
# @param [String] name Name of unit to redefine
# @param [Proc] _block
# @raise [ArgumentError] if a block is not given
# @yieldparam [RubyUnits::Unit::Definition] the definition of the unit being
# redefined
# @return (see RubyUnits::Unit.define)
def self.redefine!(name, &_block)
raise ArgumentError, "A block is required to redefine a unit" unless block_given?
unit_definition = definition(name)
raise(ArgumentError, "'#{name}' Unit not recognized") unless unit_definition
yield unit_definition
definitions.delete("<#{name}>")
define(unit_definition)
setup
end
# Undefine a unit. Will not raise an exception for unknown units.
#
# @param unit [String] name of unit to undefine
# @return (see RubyUnits::Unit.setup)
def self.undefine!(unit)
definitions.delete("<#{unit}>")
setup
end
# Unit cache
#
# @return [RubyUnits::Cache]
def self.cached
@cached ||= RubyUnits::Cache.new
end
# @return [Boolean]
def self.clear_cache
cached.clear
base_unit_cache.clear
new(1)
true
end
# @return [RubyUnits::Cache]
def self.base_unit_cache
@base_unit_cache ||= RubyUnits::Cache.new
end
# @example parse strings
# "1 minute in seconds"
# @param [String] input
# @return [Unit]
def self.parse(input)
first, second = input.scan(/(.+)\s(?:in|to|as)\s(.+)/i).first
second.nil? ? new(first) : new(first).convert_to(second)
end
# @param q [Numeric] quantity
# @param n [Array] numerator
# @param d [Array] denominator
# @return [Hash]
def self.eliminate_terms(q, n, d)
num = n.dup
den = d.dup
num.delete(UNITY)
den.delete(UNITY)
combined = ::Hash.new(0)
[[num, 1], [den, -1]].each do |array, increment|
array.chunk_while { |elt_before, _| definition(elt_before).prefix? }
.to_a
.each { combined[_1] += increment }
end
num = []
den = []
combined.each do |key, value|
if value.positive?
value.times { num << key }
elsif value.negative?
value.abs.times { den << key }
end
end
num = UNITY_ARRAY if num.empty?
den = UNITY_ARRAY if den.empty?
{ scalar: q, numerator: num.flatten, denominator: den.flatten }
end
# Creates a new unit from the current one with all common terms eliminated.
#
# @return [RubyUnits::Unit]
def eliminate_terms
self.class.new(self.class.eliminate_terms(@scalar, @numerator, @denominator))
end
# return an array of base units
# @return [Array]
def self.base_units
@base_units ||= definitions.dup.select { |_, definition| definition.base? }.keys.map { new(_1) }
end
# Parse a string consisting of a number and a unit string
# NOTE: This does not properly handle units formatted like '12mg/6ml'
#
# @param [String] string
# @return [Array(Numeric, String)] consisting of [number, "unit"]
def self.parse_into_numbers_and_units(string)
num, unit = string.scan(ANY_NUMBER_REGEX).first
[
case num
when nil # This happens when no number is passed and we are parsing a pure unit string
1
when COMPLEX_NUMBER
num.to_c
when RATIONAL_NUMBER
# We use this method instead of relying on `to_r` because it does not
# handle improper fractions correctly.
sign = Regexp.last_match(1) == "-" ? -1 : 1
n = Regexp.last_match(2).to_i
f = Rational(Regexp.last_match(3).to_i, Regexp.last_match(4).to_i)
sign * (n + f)
else
num.to_f
end,
unit.to_s.strip
]
end
# return a fragment of a regex to be used for matching units or reconstruct it if hasn't been used yet.
# Unit names are reverse sorted by length so the regexp matcher will prefer longer and more specific names
# @return [String]
def self.unit_regex
@unit_regex ||= unit_map.keys.sort_by { [_1.length, _1] }.reverse.join("|")
end
# return a regex used to match units
# @return [Regexp]
def self.unit_match_regex
@unit_match_regex ||= /(#{prefix_regex})??(#{unit_regex})\b/
end
# return a regexp fragment used to match prefixes
# @return [String]
# @private
def self.prefix_regex
@prefix_regex ||= prefix_map.keys.sort_by { [_1.length, _1] }.reverse.join("|")
end
# Generates (and memoizes) a regexp matching any of the temperature units or their aliases.
#
# @return [Regexp]
def self.temp_regex
@temp_regex ||= begin
temp_units = %w[tempK tempC tempF tempR degK degC degF degR]
aliases = temp_units.map do |unit|
d = definition(unit)
d&.aliases
end.flatten.compact
regex_str = aliases.empty? ? "(?!x)x" : aliases.join("|")
Regexp.new "(?:#{regex_str})"
end
end
# inject a definition into the internal array and set it up for use
#
# @param definition [RubyUnits::Unit::Definition]
def self.use_definition(definition)
@unit_match_regex = nil # invalidate the unit match regex
@temp_regex = nil # invalidate the temp regex
if definition.prefix?
prefix_values[definition.name] = definition.scalar
definition.aliases.each { prefix_map[_1] = definition.name }
@prefix_regex = nil # invalidate the prefix regex
else
unit_values[definition.name] = {}
unit_values[definition.name][:scalar] = definition.scalar
unit_values[definition.name][:numerator] = definition.numerator if definition.numerator
unit_values[definition.name][:denominator] = definition.denominator if definition.denominator
definition.aliases.each { unit_map[_1] = definition.name }
@unit_regex = nil # invalidate the unit regex
end
end
include Comparable
# @return [Numeric]
attr_accessor :scalar
# @return [Array]
attr_accessor :numerator
# @return [Array]
attr_accessor :denominator
# @return [Integer]
attr_accessor :signature
# @return [Numeric]
attr_accessor :base_scalar
# @return [Array]
attr_accessor :base_numerator
# @return [Array]
attr_accessor :base_denominator
# @return [String]
attr_accessor :output
# @return [String]
attr_accessor :unit_name
# Used to copy one unit to another
# @param from [RubyUnits::Unit] Unit to copy definition from
# @return [RubyUnits::Unit]
def copy(from)
@scalar = from.scalar
@numerator = from.numerator
@denominator = from.denominator
@base = from.base?
@signature = from.signature
@base_scalar = from.base_scalar
@unit_name = from.unit_name
self
end
# Create a new Unit object. Can be initialized using a String, a Hash, an Array, Time, DateTime
#
# @example Valid options include:
# "5.6 kg*m/s^2"
# "5.6 kg*m*s^-2"
# "5.6 kilogram*meter*second^-2"
# "2.2 kPa"
# "37 degC"
# "1" -- creates a unitless constant with value 1
# "GPa" -- creates a unit with scalar 1 with units 'GPa'
# "6'4\""" -- recognized as 6 feet + 4 inches
# "8 lbs 8 oz" -- recognized as 8 lbs + 8 ounces
# [1, 'kg']
# {scalar: 1, numerator: 'kg'}
#
# @param [Unit,String,Hash,Array,Date,Time,DateTime] options
# @return [Unit]
# @raise [ArgumentError] if absolute value of a temperature is less than absolute zero
# @raise [ArgumentError] if no unit is specified
# @raise [ArgumentError] if an invalid unit is specified
def initialize(*options)
@scalar = nil
@base_scalar = nil
@unit_name = nil
@signature = nil
@output = {}
raise ArgumentError, "Invalid Unit Format" if options[0].nil?
if options.size == 2
# options[0] is the scalar
# options[1] is a unit string
cached = self.class.cached.get(options[1])
if cached.nil?
initialize("#{options[0]} #{options[1]}")
else
copy(cached * options[0])
end
return
end
if options.size == 3
options[1] = options[1].join if options[1].is_a?(Array)
options[2] = options[2].join if options[2].is_a?(Array)
cached = self.class.cached.get("#{options[1]}/#{options[2]}")
if cached.nil?
initialize("#{options[0]} #{options[1]}/#{options[2]}")
else
copy(cached) * options[0]
end
return
end
case options[0]
when Unit
copy(options[0])
return
when Hash
@scalar = options[0][:scalar] || 1
@numerator = options[0][:numerator] || UNITY_ARRAY
@denominator = options[0][:denominator] || UNITY_ARRAY
@signature = options[0][:signature]
when Array
initialize(*options[0])
return
when Numeric
@scalar = options[0]
@numerator = @denominator = UNITY_ARRAY
when Time
@scalar = options[0].to_f
@numerator = ["<second>"]
@denominator = UNITY_ARRAY
when DateTime, Date
@scalar = options[0].ajd
@numerator = ["<day>"]
@denominator = UNITY_ARRAY
when /^\s*$/
raise ArgumentError, "No Unit Specified"
when String
parse(options[0])
else
raise ArgumentError, "Invalid Unit Format"
end
update_base_scalar
raise ArgumentError, "Temperatures must not be less than absolute zero" if temperature? && base_scalar.negative?
unary_unit = units || ""
if options.first.instance_of?(String)
_opt_scalar, opt_units = self.class.parse_into_numbers_and_units(options[0])
if !(self.class.cached.keys.include?(opt_units) ||
(opt_units =~ %r{\D/[\d+.]+}) ||
(opt_units =~ %r{(#{self.class.temp_regex})|(#{STONE_LB_UNIT_REGEX})|(#{LBS_OZ_UNIT_REGEX})|(#{FEET_INCH_UNITS_REGEX})|%|(#{TIME_REGEX})|i\s?(.+)?|±|\+/-})) && (opt_units && !opt_units.empty?)
self.class.cached.set(opt_units, scalar == 1 ? self : opt_units.to_unit)
end
end
unless self.class.cached.keys.include?(unary_unit) || (unary_unit =~ self.class.temp_regex)
self.class.cached.set(unary_unit, scalar == 1 ? self : unary_unit.to_unit)
end
[@scalar, @numerator, @denominator, @base_scalar, @signature, @base].each(&:freeze)
super()
end
# @todo: figure out how to handle :counting units. This method should probably return :counting instead of :unitless for 'each'
# return the kind of the unit (:mass, :length, etc...)
# @return [Symbol]
def kind
self.class.kinds[signature]
end
# Convert the unit to a Unit, possibly performing a conversion.
# > The ability to pass a Unit to convert to was added in v3.0.0 for
# > consistency with other uses of #to_unit.
#
# @param other [RubyUnits::Unit, String] unit to convert to
# @return [RubyUnits::Unit]
def to_unit(other = nil)
other ? convert_to(other) : self
end
alias unit to_unit
# Is this unit in base form?
# @return [Boolean]
def base?
return @base if defined? @base
@base = (@numerator + @denominator)
.compact
.uniq
.map { self.class.definition(_1) }
.all? { _1.unity? || _1.base? }
@base
end
alias is_base? base?
# convert to base SI units
# results of the conversion are cached so subsequent calls to this will be fast
# @return [Unit]
# @todo this is brittle as it depends on the display_name of a unit, which can be changed
def to_base
return self if base?
if self.class.unit_map[units] =~ /\A<(?:temp|deg)[CRF]>\Z/
@signature = self.class.kinds.key(:temperature)
base = if temperature?
convert_to("tempK")
elsif degree?
convert_to("degK")
end
return base
end
cached_unit = self.class.base_unit_cache.get(units)
return cached_unit * scalar unless cached_unit.nil?
num = []
den = []
q = Rational(1)
@numerator.compact.each do |num_unit|
if self.class.prefix_values[num_unit]
q *= self.class.prefix_values[num_unit]
else
q *= self.class.unit_values[num_unit][:scalar] if self.class.unit_values[num_unit]
num << self.class.unit_values[num_unit][:numerator] if self.class.unit_values[num_unit] && self.class.unit_values[num_unit][:numerator]
den << self.class.unit_values[num_unit][:denominator] if self.class.unit_values[num_unit] && self.class.unit_values[num_unit][:denominator]
end
end
@denominator.compact.each do |num_unit|
if self.class.prefix_values[num_unit]
q /= self.class.prefix_values[num_unit]
else
q /= self.class.unit_values[num_unit][:scalar] if self.class.unit_values[num_unit]
den << self.class.unit_values[num_unit][:numerator] if self.class.unit_values[num_unit] && self.class.unit_values[num_unit][:numerator]
num << self.class.unit_values[num_unit][:denominator] if self.class.unit_values[num_unit] && self.class.unit_values[num_unit][:denominator]
end
end
num = num.flatten.compact
den = den.flatten.compact
num = UNITY_ARRAY if num.empty?
base = self.class.new(self.class.eliminate_terms(q, num, den))
self.class.base_unit_cache.set(units, base)
base * @scalar
end
alias base to_base
# Generate human readable output.
# If the name of a unit is passed, the unit will first be converted to the target unit before output.
# some named conversions are available
#
# @example
# unit.to_s(:ft) - outputs in feet and inches (e.g., 6'4")
# unit.to_s(:lbs) - outputs in pounds and ounces (e.g, 8 lbs, 8 oz)
#
# You can also pass a standard format string (i.e., '%0.2f')
# or a strftime format string.
#
# output is cached so subsequent calls for the same format will be fast
#
# @note Rational scalars that are equal to an integer will be represented as integers (i.e, 6/1 => 6, 4/2 => 2, etc..)
# @param [Symbol] target_units
# @param [Float] precision - the precision to use when converting to a rational
# @param format [Symbol] Set to :exponential to force all units to be displayed in exponential format
#
# @return [String]
def to_s(target_units = nil, precision: 0.0001, format: RubyUnits.configuration.format)
out = @output[target_units]
return out if out
separator = RubyUnits.configuration.separator
case target_units
when :ft
feet, inches = convert_to("in").scalar.abs.divmod(12)
improper, frac = inches.divmod(1)
frac = frac.zero? ? "" : "-#{frac.rationalize(precision)}"
out = "#{negative? ? '-' : nil}#{feet}'#{improper}#{frac}\""
when :lbs
pounds, ounces = convert_to("oz").scalar.abs.divmod(16)
improper, frac = ounces.divmod(1)
frac = frac.zero? ? "" : "-#{frac.rationalize(precision)}"
out = "#{negative? ? '-' : nil}#{pounds}#{separator}lbs #{improper}#{frac}#{separator}oz"
when :stone
stone, pounds = convert_to("lbs").scalar.abs.divmod(14)
improper, frac = pounds.divmod(1)
frac = frac.zero? ? "" : "-#{frac.rationalize(precision)}"
out = "#{negative? ? '-' : nil}#{stone}#{separator}stone #{improper}#{frac}#{separator}lbs"
when String
out = case target_units.strip
when /\A\s*\Z/ # whitespace only
""
when /(%[-+.\w#]+)\s*(.+)*/ # format string like '%0.2f in'
begin
if Regexp.last_match(2) # unit specified, need to convert
convert_to(Regexp.last_match(2)).to_s(Regexp.last_match(1), format: format)
else
"#{Regexp.last_match(1) % @scalar}#{separator}#{Regexp.last_match(2) || units(format: format)}".strip
end
rescue StandardError # parse it like a strftime format string
(DateTime.new(0) + self).strftime(target_units)
end
when /(\S+)/ # unit only 'mm' or '1/mm'
convert_to(Regexp.last_match(1)).to_s(format: format)
else
raise "unhandled case"
end
else
out = case @scalar
when Complex
"#{@scalar}#{separator}#{units(format: format)}"
when Rational
"#{@scalar == @scalar.to_i ? @scalar.to_i : @scalar}#{separator}#{units(format: format)}"
else
"#{'%g' % @scalar}#{separator}#{units(format: format)}"
end.strip
end
@output[target_units] = out
out
end
# Normally pretty prints the unit, but if you really want to see the guts of it, pass ':dump'
# @deprecated
# @return [String]
def inspect(dump = nil)
return super() if dump
to_s
end
# true if unit is a 'temperature', false if a 'degree' or anything else
# @return [Boolean]
# @todo use unit definition to determine if it's a temperature instead of a regex
def temperature?
degree? && units.match?(self.class.temp_regex)
end
alias is_temperature? temperature?
# true if a degree unit or equivalent.
# @return [Boolean]
def degree?
kind == :temperature
end
alias is_degree? degree?
# returns the 'degree' unit associated with a temperature unit
# @example '100 tempC'.to_unit.temperature_scale #=> 'degC'
# @return [String] possible values: degC, degF, degR, or degK
def temperature_scale
return nil unless temperature?
"deg#{self.class.unit_map[units][/temp([CFRK])/, 1]}"
end
# returns true if no associated units
# false, even if the units are "unitless" like 'radians, each, etc'
# @return [Boolean]
def unitless?
@numerator == UNITY_ARRAY && @denominator == UNITY_ARRAY
end
# Compare two Unit objects. Throws an exception if they are not of compatible types.
# Comparisons are done based on the value of the unit in base SI units.
# @param [Object] other
# @return [Integer,nil]
# @raise [NoMethodError] when other does not define <=>
# @raise [ArgumentError] when units are not compatible
def <=>(other)
raise NoMethodError, "undefined method `<=>' for #{base_scalar.inspect}" unless base_scalar.respond_to?(:<=>)
if other.nil?
base_scalar <=> nil
elsif !temperature? && other.respond_to?(:zero?) && other.zero?
base_scalar <=> 0
elsif other.instance_of?(Unit)
raise ArgumentError, "Incompatible Units ('#{units}' not compatible with '#{other.units}')" unless self =~ other
base_scalar <=> other.base_scalar
else
x, y = coerce(other)
y <=> x
end
end
# Compare Units for equality
# this is necessary mostly for Complex units. Complex units do not have a <=> operator
# so we define this one here so that we can properly check complex units for equality.
# Units of incompatible types are not equal, except when they are both zero and neither is a temperature
# Equality checks can be tricky since round off errors may make essentially equivalent units
# appear to be different.
# @param [Object] other
# @return [Boolean]
def ==(other)
if other.respond_to?(:zero?) && other.zero?
zero?
elsif other.instance_of?(Unit)
return false unless self =~ other
base_scalar == other.base_scalar
else
begin
x, y = coerce(other)
x == y
rescue ArgumentError # return false when object cannot be coerced
false
end
end
end
# Check to see if units are compatible, ignoring the scalar part. This check is done by comparing unit signatures
# for performance reasons. If passed a string, this will create a [Unit] object with the string and then do the
# comparison.
#
# @example this permits a syntax like:
# unit =~ "mm"
# @note if you want to do a regexp comparison of the unit string do this ...
# unit.units =~ /regexp/
# @param [Object] other
# @return [Boolean]
def =~(other)
return signature == other.signature if other.is_a?(Unit)
x, y = coerce(other)
x =~ y
rescue ArgumentError # return false when `other` cannot be converted to a [Unit]
false
end
alias compatible? =~
alias compatible_with? =~
# Compare two units. Returns true if quantities and units match
# @example
# RubyUnits::Unit.new("100 cm") === RubyUnits::Unit.new("100 cm") # => true
# RubyUnits::Unit.new("100 cm") === RubyUnits::Unit.new("1 m") # => false
# @param [Object] other
# @return [Boolean]
def ===(other)
case other
when Unit
(scalar == other.scalar) && (units == other.units)
else
begin
x, y = coerce(other)
x.same_as?(y)
rescue ArgumentError
false
end
end
end
alias same? ===
alias same_as? ===
# Add two units together. Result is same units as receiver and scalar and base_scalar are updated appropriately
# throws an exception if the units are not compatible.
# It is possible to add Time objects to units of time
# @param [Object] other
# @return [Unit]
# @raise [ArgumentError] when two temperatures are added
# @raise [ArgumentError] when units are not compatible
# @raise [ArgumentError] when adding a fixed time or date to a time span
def +(other)
case other
when Unit
if zero?
other.dup
elsif self =~ other
raise ArgumentError, "Cannot add two temperatures" if [self, other].all?(&:temperature?)
if temperature?
self.class.new(scalar: (scalar + other.convert_to(temperature_scale).scalar), numerator: @numerator, denominator: @denominator, signature: @signature)
elsif other.temperature?
self.class.new(scalar: (other.scalar + convert_to(other.temperature_scale).scalar), numerator: other.numerator, denominator: other.denominator, signature: other.signature)
else
self.class.new(scalar: (base_scalar + other.base_scalar), numerator: base.numerator, denominator: base.denominator, signature: @signature).convert_to(self)
end
else
raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')"
end
when Date, Time
raise ArgumentError, "Date and Time objects represent fixed points in time and cannot be added to a Unit"
else
x, y = coerce(other)
y + x
end
end
# Subtract two units. Result is same units as receiver and scalar and base_scalar are updated appropriately
# @param [Numeric] other
# @return [Unit]
# @raise [ArgumentError] when subtracting a temperature from a degree
# @raise [ArgumentError] when units are not compatible
# @raise [ArgumentError] when subtracting a fixed time from a time span
def -(other)
case other
when Unit
if zero?
if other.zero?
other.dup * -1 # preserve Units class
else
-other.dup
end
elsif self =~ other
if [self, other].all?(&:temperature?)
self.class.new(scalar: (base_scalar - other.base_scalar), numerator: KELVIN, denominator: UNITY_ARRAY, signature: @signature).convert_to(temperature_scale)
elsif temperature?
self.class.new(scalar: (base_scalar - other.base_scalar), numerator: ["<tempK>"], denominator: UNITY_ARRAY, signature: @signature).convert_to(self)
elsif other.temperature?
raise ArgumentError, "Cannot subtract a temperature from a differential degree unit"
else
self.class.new(scalar: (base_scalar - other.base_scalar), numerator: base.numerator, denominator: base.denominator, signature: @signature).convert_to(self)
end
else
raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')"
end
when Time
raise ArgumentError, "Date and Time objects represent fixed points in time and cannot be subtracted from a Unit"
else
x, y = coerce(other)
y - x
end
end
# Multiply two units.
# @param [Numeric] other
# @return [Unit]
# @raise [ArgumentError] when attempting to multiply two temperatures
def *(other)
case other
when Unit
raise ArgumentError, "Cannot multiply by temperatures" if [other, self].any?(&:temperature?)
opts = self.class.eliminate_terms(@scalar * other.scalar, @numerator + other.numerator, @denominator + other.denominator)
opts[:signature] = @signature + other.signature
self.class.new(opts)
when Numeric
self.class.new(scalar: @scalar * other, numerator: @numerator, denominator: @denominator, signature: @signature)
else
x, y = coerce(other)
x * y
end
end
# Divide two units.
# Throws an exception if divisor is 0
# @param [Numeric] other
# @return [Unit]
# @raise [ZeroDivisionError] if divisor is zero
# @raise [ArgumentError] if attempting to divide a temperature by another temperature
def /(other)
case other
when Unit
raise ZeroDivisionError if other.zero?
raise ArgumentError, "Cannot divide with temperatures" if [other, self].any?(&:temperature?)
sc = Rational(@scalar, other.scalar)
sc = sc.numerator if sc.denominator == 1
opts = self.class.eliminate_terms(sc, @numerator + other.denominator, @denominator + other.numerator)
opts[:signature] = @signature - other.signature
self.class.new(opts)
when Numeric
raise ZeroDivisionError if other.zero?
sc = Rational(@scalar, other)
sc = sc.numerator if sc.denominator == 1
self.class.new(scalar: sc, numerator: @numerator, denominator: @denominator, signature: @signature)
else
x, y = coerce(other)
y / x
end
end
# Returns the remainder when one unit is divided by another
#
# @param [Unit] other
# @return [Unit]
# @raise [ArgumentError] if units are not compatible
def remainder(other)
raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" unless compatible_with?(other)
self.class.new(base_scalar.remainder(other.to_unit.base_scalar), to_base.units).convert_to(self)
end
# Divide two units and return quotient and remainder
#
# @param [Unit] other
# @return [Array(Integer, Unit)]
# @raise [ArgumentError] if units are not compatible
def divmod(other)
raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" unless compatible_with?(other)