rubyintegernegative-numbernegative-integer

Ruby, making a number negative


This is probably super basic, but I've tried enough things that have failed to reach out..

I want to change a number to it's negative version.

answer = []
array = [3, 5, 2, 19, 2, 1]

array.each.with_index do |x, i|

   if x > array[i+1]
      answer << array[i] * -1
   else x =< array[i+1]
      answer << array[i] 
   end
 end
=> the answer I want is [-5] for when 'true' but I'm getting [5]

I also tried making a new 'negarray' with all the equivalent negative numbers as 'array'

answer = []
array = [3, 5, 2, 19, 2, 1]
negarray = [-3, -5, -2, -19, -2, -1]

=> again, getting [5], and not the [-5] I want. 

Cheers!


Solution

  • In the actual version the questions is unclear.

    If you mean with

    I want to change a number to it's negative version.

    that you want always a negative number, then you could try:

    answer = []
    array = [3, 5, 6, 19, 2, 1]
    
    array.each do |x|
       if x > 0
          answer << x * -1
       else
          answer << x 
       end
     end
    
     p answer
    

    or

    array.each do |x|
       answer << if x > 0
           x * -1
       else
           x 
       end
     end
    

    or with a ternary operator:

    array.each do |x|
       answer << (x > 0 ? -x : x)
     end
    

    Or shorter and more ruby-esk (using a ternary operator):

     array = [3, 5, 6, 19, 2, -1]
     answer = array.map { |n| n > 0 ? -n : n }
    

    If you prefer the longer if:

     answer = array.map do |n| 
      if n > 0 
        -n 
      else
        n 
      end
     end
    

    If you don't want to use any if-structure, then you could use a negative abs-method:

     answer = array.map { |n| -n.abs }