2021-04-10 21:06:28 +02:00
|
|
|
# A ruby program to add numbers
|
|
|
|
# Addition or sum of numbers means adding each and every element of the inputs
|
|
|
|
# Sum or addition of 1 and 3 is 1 + 3 = 4
|
|
|
|
|
2021-04-15 01:29:37 +02:00
|
|
|
def add(*array)
|
2021-04-10 21:06:28 +02:00
|
|
|
sum = 0
|
2021-09-03 22:24:58 +02:00
|
|
|
array.each { |a| sum += a }
|
2021-04-10 21:06:28 +02:00
|
|
|
puts "The sum of following elements #{array} is #{sum}"
|
2021-09-03 22:24:58 +02:00
|
|
|
rescue StandardError
|
|
|
|
puts 'Error: Please provide number only!'
|
2021-04-10 21:06:28 +02:00
|
|
|
end
|
|
|
|
|
2021-09-03 22:24:58 +02:00
|
|
|
#
|
2021-04-10 21:06:28 +02:00
|
|
|
# Valid inputs
|
2021-09-03 22:24:58 +02:00
|
|
|
#
|
2021-04-10 21:06:28 +02:00
|
|
|
|
2021-04-15 01:40:39 +02:00
|
|
|
puts add(1)
|
|
|
|
# The sum of following elements [1] is 1
|
|
|
|
|
|
|
|
puts add(2, 5, -4)
|
|
|
|
# The sum of following elements [2, 5, -4] is 3
|
|
|
|
|
|
|
|
puts add(25, 45)
|
|
|
|
# The sum of following elements [25, 45] is 70
|
|
|
|
|
2021-09-03 22:24:58 +02:00
|
|
|
#
|
2021-04-10 21:06:28 +02:00
|
|
|
# Invalid inputs
|
2021-09-03 22:24:58 +02:00
|
|
|
#
|
2021-04-15 01:40:39 +02:00
|
|
|
|
2021-09-03 22:24:58 +02:00
|
|
|
puts add('1', 2, 3)
|
2021-04-15 01:40:39 +02:00
|
|
|
# Error: Please provide number only!
|
|
|
|
|
2021-09-03 22:24:58 +02:00
|
|
|
puts add('a', 1)
|
2021-04-15 01:40:39 +02:00
|
|
|
# Error: Please provide number only!
|