-1

Sorry for such a naive question but can someone let me know what is the ruby way of writing the below line of code

result.nil? ? false : !result
Ali Raza
  • 3
  • 2
  • What is that line supposed to do? – Stefan Nov 01 '22 at 10:14
  • this line is returning bool based on the value of the result – Ali Raza Nov 01 '22 at 10:17
  • Right now, it returns `true` if `result` is `false`, and `false` otherwise – is that expected? – Stefan Nov 01 '22 at 10:19
  • Yes, if result is true then return false, if result is false then return true, if result is nil then return false – Ali Raza Nov 01 '22 at 10:21
  • I understand mapping `true` to `false` and vice-versa. But may I ask why you want to treat `nil` like `true`? In Ruby, `false` and `nil` are usually considered both "falsy" and everything else "truthy". – Stefan Nov 01 '22 at 10:36
  • Actually here I am routing conditionally using [Routing Constraits](https://stackoverflow.com/a/29136866/20386850) and my constrain is that if the request has `Hash A` and That hash has `field B` which then returns bool based on the value of `Hash.dig('A','B')` and if the request has nil `Hash A` then return false. – Ali Raza Nov 01 '22 at 10:49
  • Have a look at [`Hash#fetch`](https://ruby-doc.org/core-3.1.2/Hash.html#fetch-method) which allows to pass a default value if a key is missing. – Stefan Nov 01 '22 at 13:59

1 Answers1

3

According to your comment:

  • if result is true then return false
  • if result is false then return true
  • if result is nil then return false

you just need to check for result == false:

result = true
result == false #=> false

result = false
result == false #=> true

result = nil
result == false #=> false
Stefan
  • 109,145
  • 14
  • 143
  • 218