Module: Vector2d::Parsing
- Included in:
- Vector2d
- Defined in:
- lib/vector2d/parsing.rb
Overview
The permissive constructor. Everything Vector2d.parse accepts is recognized here, and turned into two coordinates the class builds a vector from. It is a module rather than a plain class method, so a subclass parses into its own kind.
Instance Method Summary collapse
-
#parse(arg, second_arg = NO_ARGUMENT) ⇒ Vector2d
Parses a vector out of any of the forms below, and is the permissive counterpart to .new, which takes exactly two coordinates.
Instance Method Details
#parse(arg, second_arg = NO_ARGUMENT) ⇒ Vector2d
Parses a vector out of any of the forms below, and is the permissive counterpart to .new, which takes exactly two coordinates. Vector2d() is shorthand for this method.
Vector2d.parse(150, 100)
Vector2d.parse(150.0, 100.0)
Vector2d.parse("150x100")
Vector2d.parse("150.0x100.0")
Vector2d.parse([150,100])
Vector2d.parse({x: 150, y: 100})
Vector2d.parse({"x" => 150.0, "y" => 100.0})
Vector2d.parse(Vector2d(150, 100))
Vector2d.parse(Vector[150, 100])
Vector2d.parse(Matrix[[150], [100]])
Strings are either "150x100" or "150,100", optionally signed and case insensitive. Coordinates keep their type, so "150x100" gives integers and "150.0x100" gives a float and an integer. An omitted coordinate is zero, as in "x100".
Vector2d.parse("-150X100") # => Vector2d(-150,100)
Vector2d.parse("150, 100") # => Vector2d(150,100)
Vector2d.parse("x100") # => Vector2d(0,100)
A vector is returned as it is, as long as it is an instance of the class parsing it. A vector of any other class is rebuilt, so a subclass is always handed back its own kind.
v = Vector2d(150, 100)
Vector2d.parse(v).equal?(v) # => true
Raises ArgumentError unless both coordinates resolve to real numbers. Complex numbers are not coordinates, and are rejected.
Vector2d.parse(150, nil) # => ArgumentError
Vector2d.parse(Complex(1, 2), 3) # => ArgumentError
70 71 72 73 74 |
# File 'lib/vector2d/parsing.rb', line 70 def parse(arg, second_arg = NO_ARGUMENT) return parse_single_arg(arg) if NO_ARGUMENT.equal?(second_arg) build(coordinate(arg), coordinate(second_arg)) end |