0
    if firstcheck? || secondcheck?
      nil
    else
      true
    end

How can i reduce this block of code to one single line? If the condition is correct i need to return nil, else true

Please help

  • Use ternary operator, you can chain them if there are more conditions to check for. –  May 25 '17 at 21:47
  • When asking, we expect to see evidence of your effort. Without that it looks like you didn't try and want us to write it for you. – the Tin Man May 25 '17 at 21:56
  • I already wrote a bunch of code. But this is just a small case, so I thought why to create confusion by adding unnecceary data too.Sorry if i done anything wrong – norman bates May 25 '17 at 22:05
  • Clearly this question is not a duplicate of "How do I use the conditional operator?" since you can give a good answer to it that doesn't involve the conditional operator. – David Grayson May 25 '17 at 22:16

1 Answers1

3

This line is equivalent to the snippet of code you wrote:

true unless firstcheck? || secondcheck?

I have to wonder if you really have a requirement to return nil instead of false. If you are OK with returning false instead of nil, you could write it as:

!firstcheck? && !secondcheck?
David Grayson
  • 84,103
  • 24
  • 152
  • 189
  • Thanks for the answer. I need to return nil instead of false.How does the first statement return nil? – norman bates May 25 '17 at 22:00
  • I'd use `!(firstcheck? || secondcheck?)` instead of `!firstcheck? && !secondcheck?` – the Tin Man May 25 '17 at 22:15
  • norman bates: That's just how Ruby works. `... unless true` always evaluates to `nil` since it has to have some value. Similarly, `... if false` always evaluates to `nil`. – David Grayson May 25 '17 at 22:19
  • I think `firstcheck? || secondcheck? ? nil : true` reads best. If characters are precious, you could write `!(firstcheck? || secondcheck?) || nil`. ¯\\_(ツ)_/¯ – Cary Swoveland May 26 '17 at 06:53