Search code examples
rubymapreducekeyword-argumentsplat

Ruby - Reduce array of numbers in ruby returns strange result


I'm trying to write a method called calculate which determine to add or subtract numbers depending on a keyword argument passed to it.

Here're the methods:

def add(*num)
  num.inject(:+)
end

def subtract(*num)
  num.reduce(:-)
end

def calculate(*num, **op)
  return add(num) if op[:add] || op.empty?
  return subtract(num) if op[:subtract]
end

puts calculate(1, 2, 3, add: true)
puts calculate(1, 2, 3, subtract: true)

When I run this function, I get this result:

1
2
3

1
2
3

Solution

  • puts is your friend:

    def add(*num)
      puts "in add, num = #{num}, num.size = #{num.size}"
      num.inject(:+)
    end
    
    def calculate(*num, **op)
      puts "num = #{num}, op = #{op}"
      return add(num) if op[:add] || op.empty?
    end
    
    calculate(1, 2, 3, add: true)
      # num = [1, 2, 3], op = {:add=>true}
      # in add, num = [[1, 2, 3]], num.size = 1
      #=> nil
    

    Now fix calculate:

    def calculate(*num, **op)
      puts "num = #{num}, op = #{op}"
      return add(*num) if op[:add] || op.empty?
    end
    
    calculate(1, 2, 3, add: true)
      # num = [1, 2, 3], op = {:add=>true}
      # in add, num = [1, 2, 3], num.size = 3
      # => 6