Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def calculate(string)
- splitted = split_string_by_operators(string)
- parsed = parse_to_nums(splitted)
- splitted = split_by_minus_or_plus(parsed)
- almost_end = splitted.map! {|elem| eval_each_three(elem)}.flatten!
- eval_each_three(almost_end)
- end
- def split_string_by_operators(string)
- string.split(%r{(\+|\-|\/|\*)}).map do |x|
- unless x =~ /(\+|\-|\/|\*)/
- x.to_f
- else
- x
- end
- end
- end
- def split_by_minus_or_plus(array)
- result = []
- second_prior_operators = array.count("+") + array.count('-')
- (second_prior_operators+1).times do
- result << []
- end
- ind = 0
- array.each do |token|
- if token != "+" || token != '-'
- result[ind].push(token)
- p result
- else
- result.insert(ind, token)
- #puts result
- ind += 1
- end
- end
- result
- end
- def eval_each_three(ary)
- result = 0
- while ary.size != 1
- result = calc(ary[0], ary[1], ary[2])
- 3.times do
- ary.shift
- end
- ary.unshift(result)
- end
- ary
- end
- #[982.0, "*", 5.0, "+", 3.0, "/", 5.0, "-", 1.0]
- def calc(num1, operator, num2)
- case operator
- when "*"
- num1 * num2
- when "-"
- num1 - num2
- when "/"
- num1.to_f / num2
- when "+"
- num1 + num2
- end
- end
- def parse_to_nums(ary)
- ary.map! do |token|
- if token =~ /\d/
- token.to_i
- else
- token
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement