-2

For example: what is this saying:

  if !result[movie[:studio]]
    result[movie[:studio]] = movie[:worldwide_gross]
  else
    result[movie[:studio]] += movie[:worldwide_gross]
  end
  i += 1
end

This is a solution to manipulating an NDS, or rather getting some information from an NDS and I can't seem to find what the !result means.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • result was a locally defined variable in the method, a hash, that is being called on to collect the amount of money what the keys point to have earned – Ryan Tom Anderson Mar 18 '20 at 01:13
  • 1
    Same as any other language, negation. This code could be written more clearly because you can omit the `!` operator and swap the blocks. – ggorlen Mar 18 '20 at 01:15
  • 1
    `!result` means "not result", or "if result is false" – FoggyDay Mar 18 '20 at 01:18
  • got it, not sure why i wasn't finding that in searches. thanks! – Ryan Tom Anderson Mar 18 '20 at 01:28
  • 3
    I googled "ruby exclamation mark". The second hit was [this](https://stackoverflow.com/questions/27882546/exclamation-points-before-a-variable-in-ruby), which answers your question. Did you research your question before asking? – Cary Swoveland Mar 18 '20 at 03:14
  • 2
    This is covered in Ruby tutorials. – the Tin Man Mar 18 '20 at 06:14
  • That's [`BasicObject#!`](https://ruby-doc.org/core-2.7.0/BasicObject.html#method-i-21) – it returns `true` if the object is `false` or `nil`, and `false` otherwise. – Stefan Mar 18 '20 at 07:19

2 Answers2

0

The ! negates the element. So if result[movie[:studio]] is truthy then !result[movie[:studio]] is the opposite, falsy. Your conditional statement is basically saying that if there is no value for the studio key then give it a value of movie[:worldwide_gross], otherwise add to the current value.

If you do not like the ! you could consider using unless instead or swap the order of the conditional.

if result[movie[:studio]]
  result[movie[:studio]] += movie[:worldwide_gross]
else
  result[movie[:studio]] = movie[:worldwide_gross]
end
aburr
  • 81
  • 5
0

! negates the element as it was already mentioned.

So, !true => false

So if you do

if !hungry 
 do x
end

You will execute X if you are not hungry.

It might also be used on null. So you can use it to check if "not null". This might be the use case that you're seeing.

Noel
  • 966
  • 1
  • 9
  • 19