-4

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!

Viola Crellin
  • 61
  • 2
  • 8

3 Answers3

4

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 }
knut
  • 27,320
  • 6
  • 84
  • 112
4

WIth the following line

if x > array[i+1]

You are basically saying if the element at position i is greater than the position at i+1, you want to make it negative. The problem is that 5 is smaller than the next element 6 and for that reason it isn't being negated.

Let's fix up your code, and use the map method to simplify it:

out = array.map.with_index do |x, i|
   (array[i+1].nil? || x > array[i+1]) ? x : x*-1
end
# [-3, -5, -6, 19, 2, 1]
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • Thanks Martin, I actually ballsed up my example there. I should have chose a different number to 5 to illustrate my point. Apologies. Thanks for your much neater solution though! – Viola Crellin Jan 09 '16 at 21:49
-1

If you want to get the negative value of the second array element at index 1, do the following

answer << array[1] * -1

In order to change ALL values of an array to negative numbers, use the following

answer = array.map { |n| -n }
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87