lib/rdf/model/literal/double.rb in rdf-0.3.0.pre vs lib/rdf/model/literal/double.rb in rdf-0.3.0

- old
+ new

@@ -12,22 +12,29 @@ # @since 0.2.1 class Double < Literal DATATYPE = XSD.double GRAMMAR = /^[\+\-]?\d+(\.\d*([eE][\+\-]?\d+)?)?$/.freeze # FIXME: support 'INF', '-INF' and 'NaN' + include RDF::Literal::Numeric + ## # @param [Float, #to_f] value # @option options [String] :lexical (nil) def initialize(value, options = {}) @datatype = RDF::URI(options[:datatype] || DATATYPE) @string = options[:lexical] if options.has_key?(:lexical) @string = value if !defined?(@string) && value.is_a?(String) @object = case - when value.is_a?(::String) then Float(value) rescue nil + when value.is_a?(::String) then case value + when 'INF' then 1/0.0 + when '-INF' then -1/0.0 + when 'NaN' then 0/0.0 + else Float(value) rescue nil + end when value.is_a?(::Float) then value when value.respond_to?(:to_f) then value.to_f - else Float(value.to_s) rescue nil + else Float(value.to_s) rescue nil # FIXME end end ## # Converts this literal into its canonical lexical representation. @@ -45,11 +52,12 @@ i, f, e = ('%.16E' % @object.to_f).split(/[\.E]/) f.sub!(/0*$/, '') # remove any trailing zeroes f = '0' if f.empty? # ...but there must be a digit to the right of the decimal point e.sub!(/^\+?0+(\d)$/, '\1') # remove the optional leading '+' sign and any extra leading zeroes "#{i}.#{f}E#{e}" - end unless @object.nil? + end + @object = Float(@string) unless @object.nil? self end ## # Compares this literal to `other` for sorting purposes. @@ -57,11 +65,11 @@ # @param [Object] other # @return [Integer] `-1`, `0`, or `1` # @since 0.3.0 def <=>(other) case other - when Numeric + when ::Numeric to_d <=> other when RDF::Literal::Decimal, RDF::Literal::Double to_d <=> other.to_d else super end @@ -72,11 +80,11 @@ # # @param [Object] other # @return [Boolean] `true` or `false` # @since 0.3.0 def ==(other) - (self <=> other).zero? + (cmp = (self <=> other)) ? cmp.zero? : false end alias_method :===, :== ## # Returns `true` if the value is an invalid IEEE floating point number. @@ -192,10 +200,10 @@ # Returns `self` negated. # # @return [RDF::Literal] # @since 0.2.3 def -@ - RDF::Literal(-to_f) # unary minus + RDF::Literal(-to_f, :datatype => datatype) # unary minus end ## # Returns the sum of `self` plus `other`. #