2

I'm working through the Ruby on Rails tutorial, and I'm curious about this codeblock:

if remember_digest.nil?
    false
else
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
end

is there a difference between if remember_digest.nil? and if remember_digest == nil, or is this just the author's preference?

spickermann
  • 100,941
  • 9
  • 101
  • 131
  • 1
    While the result might be the same would like to mention, that `== nil` is uncommon in Ruby, `nil?` is a more common Ruby idiom. And since `nil` is `falsey` you could also write `unless remember_digest` (without any further method calls) – spickermann May 17 '16 at 19:55
  • I agree with @spickermann also there is an actual difference `Object#nil?` simply responds with `Qfalse` and `NilClass#nil?` is the only class that overrides this with `Qtrue` where as `==` will actually perform a comparison so while the result is the same the former has a lesser impact on the interpreter (albeit extremely minimal). – engineersmnky May 17 '16 at 19:58
  • 1
    @engineersmnky `Qfalse` and such are really only relevant as C internals. `NilClass` (`nil`) and `FalseClass` (`false`) are their actual representations within Ruby. – tadman May 17 '16 at 20:10
  • Given `remember_digest` might reasonably be a `true` or `false` value you probably don't want to test vs `nil` specifically. You might want to do: `remember_digest and BCrypt::Password.new(...)` – tadman May 17 '16 at 20:11

1 Answers1

2

No difference. According to docs, only nil object responds true to nil?.

spickermann
  • 100,941
  • 9
  • 101
  • 131
Ilya
  • 13,337
  • 5
  • 37
  • 53