Method: Fractify::Fraction.validate_string

Defined in:
lib/fractify/fraction.rb

.validate_string(string) ⇒ Object



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
# File 'lib/fractify/fraction.rb', line 309

def self.validate_string(string)
  stage = 0
  open_bracket, incorrect_syntax, at_end, digit_present = false
  minus_is_free = true

  string.each_char do |c|
    if at_end || letter?(c)
      incorrect_syntax = true
      break
    end

    if open_bracket
      if stage.zero?
        if c == '-' && minus_is_free
          minus_is_free = false
        elsif numeric?(c)
          digit_present = true
        elsif c == ' ' && digit_present
          stage = 1
          minus_is_free = true
          digit_present = false
        elsif c == '/' && digit_present
          stage = 2
          minus_is_free = true
          digit_present = false
        elsif c == ')' && digit_present
        else
          incorrect_syntax = true
          break
        end
      elsif stage == 1
        if c == '-' && minus_is_free
          minus_is_free = false
        elsif numeric?(c)
          digit_present = true
        elsif c == '/' && digit_present
          stage = 2
          minus_is_free = true
          digit_present
        else
          incorrect_syntax = true
          break
        end
      elsif stage == 2
        if c == '-' && minus_is_free
          minus_is_free = false
        elsif numeric?(c)
          digit_present = true
        elsif c == ')' && digit_present
        else
          incorrect_syntax = true
          break
        end
      end
    end

    if c == '('
      if open_bracket
        incorrect_syntax = true
        break
      end
      open_bracket = true
    elsif c == ')'
      unless open_bracket
        incorrect_syntax = true
        break
      end
      open_bracket = false
      at_end = true
    end
  end

  incorrect_syntax = true if open_bracket

  !incorrect_syntax
end