VladikOtez

Simple Parser Ruby

Sep 7th, 2017
207
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def calculate(string)
  2.   splitted = split_string_by_operators(string)
  3.   parsed = parse_to_nums(splitted)
  4.   splitted = split_by_minus_or_plus(parsed)
  5.   almost_end = splitted.map! {|elem| eval_each_three(elem)}.flatten!
  6.   eval_each_three(almost_end)
  7. end
  8.  
  9. def split_string_by_operators(string)
  10.   string.split(%r{(\+|\-|\/|\*)}).map do |x|
  11.     unless x =~ /(\+|\-|\/|\*)/
  12.       x.to_f
  13.     else
  14.       x
  15.     end
  16.   end
  17. end
  18.  
  19. def split_by_minus_or_plus(array)
  20.   result = []
  21.   second_prior_operators = array.count("+") + array.count('-')
  22.   (second_prior_operators+1).times do
  23.     result << []
  24.   end
  25.   ind = 0
  26.   array.each do |token|
  27.     if token != "+" || token != '-'
  28.       result[ind].push(token)
  29.       p result
  30.     else
  31.       result.insert(ind, token)
  32.       #puts result
  33.       ind += 1
  34.     end
  35.   end
  36.   result
  37.  
  38. end
  39.  
  40.  
  41. def eval_each_three(ary)
  42.   result = 0
  43.   while ary.size != 1
  44.     result = calc(ary[0], ary[1], ary[2])
  45.     3.times do
  46.       ary.shift
  47.     end
  48.     ary.unshift(result)
  49.   end
  50.   ary
  51. end
  52.  
  53. #[982.0, "*", 5.0, "+", 3.0, "/", 5.0, "-", 1.0]
  54.  
  55. def calc(num1, operator, num2)
  56.   case operator
  57.     when  "*"
  58.       num1 * num2
  59.     when  "-"
  60.       num1 - num2
  61.     when  "/"
  62.       num1.to_f / num2
  63.     when  "+"
  64.       num1 + num2
  65.   end
  66. end
  67.  
  68. def parse_to_nums(ary)
  69.   ary.map! do |token|
  70.     if token =~ /\d/
  71.       token.to_i
  72.     else
  73.       token
  74.     end
  75.   end
  76. end
RAW Paste Data