Subtraction question

Hello all, I’m quite new to this forum,
so forgive me if I break a few rules unknowingly

anyways, I have a question : how would one subtract a list of numbers in
a row?

for example,

a = 1
b = 7
c = 3
d = 5
e = 9

I want to subtract all the numbers in this format :

a - b - c - d - e = ?

(keep in mind that there won’t always be 5 numbers, and the numbers
won’t always be constant)

thanks in advance

–swaraj

swaraj dhumne wrote in post #1048821:

anyways, I have a question : how would one subtract a list of numbers in
a row?

What have you tried so far? Is this a homework question?

I suggest you start with putting the numbers in an array:

a = [1, 7, 3, 5, 9]

Then take the first element as the initial sum, and make a loop which
iterates over the remaining elements, subtracting them from the sum.

To get all elements apart from the first, use a[1…-1]

There are much more concise ways of doing this in Ruby, but you should
start with the simplest way, using whatever language constructs you
know. Then you can come back and ask if there is a neater way.

hello

addition is associative

2 + 3 + 7 = (2 + 3) + 7 = 2 + (3 + 7) = 12

on the contrary, subtraction is non-associative;
so (5 - 3) - 2 (=0) is not equal 5 - (3 - 2) (=4)

in other word the result depends on parenthesis;

no parenthesis means evaluating from left to right;
so…
a - b - c - d - e = ((((a - b) - c) - d) - e)

in your example -23

arr = [1, 7, 3, 5, 9]
result = arr[0]
arr[1…-1].each {|n| result -= n }
p result

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs