Variable and expressions in ruby

Go To


I am trying to create a ruby program where three numbers are entered and their sum is taken but if any numbers are the same they don't count toward the sum. example (4,5,4) = 5 My problem is with my expressions. If i enter the same number I get multiple output for various combination. example enter 5,5,5 = 15,5,0

if a != b or c then
  puts a+b+c
elsif b != a or c then
  puts a+b+c
elsif c != a or b then 
  puts a+b+c

if a == b then
  puts c
elsif a == c then
  puts b
elsif b == c then
  puts a

if a == b and c then
  puts 0
elsif b == a and c then
  puts 0
elsif c == a and b then
  puts 0
2012-04-03 22:36
by user1239333
This is how I would do: 1# Sort the Array 2# Iterate through the array, and for each element that appears only one (they will now be in runs-of-the-same-number) add it to a new array. #3 Sum the contents of the new array. (#1+#2 can be simplified with a Enumerable#group_by followed by and #3 can be done with Enumerable#reduce. - NoName 2012-04-03 22:40


Solving it with two beautiful self explanatory one-liners

array = [a,b,c]

array = array.keep_if {|item| array.count(item) == 1 }
array.inject(0){|sum,item| sum + item}

-The first line creates an array with your parameters.
-The second line only keep the items whose count equals to 1 (remove the ones that appear more than one time), and store that on the array.
-The third line sums all the remaining elements.

Voilà, the ruby way :)

2012-04-03 22:58
by Castilho
The third line can be written array.inject(0, :+). This has two advantages IMO: 1) you can tell it's only adding, and not doing anything else, much more quickly 2) it has a cute emoticon - Andrew Grimm 2012-04-04 00:05
point taken, specially for the second argument : - Castilho 2012-04-04 00:15