Hacker News new | past | comments | ask | show | jobs | submit login

I always wondered about the defined? thing too.

A rubyism is that any function suffixed with a ? should return a true/false, but then again, another rubyism is that everything that isn't explicitly False or nil evaluates to True, so it kind of works out. I can see how this would make anyone coming from another language kind of scratch their heads, though.

You'd expect defined? to return simple boolean, not evaluate the type of object being referenced (kind of like .class)




No, your conception of methods suffixed with ? is false. Methods suffixed with ? are expected to return a truthy/falsy value. nil and false are perfectly falsy in comparisons and any string will evaluate to true. So returning the type of the object in question and nil in the false case is perfectly valid and expected. It's not the only method to work that way.


As stated elsewhere in the thread, this is a clever retort but in practice defined? is the only major example I've seen where the ? suffix results in a non-boolean return value. You're arguing over a convention, and I think most people writing Ruby would be surprised to learn defined? returns a String.


It's a common misconception that ruby developers think that predicates must return a boolean value. It's still a misconception. This blog post linked elsewhere in the discussion is a good summary: http://blog.leshill.org/blog/2012/03/25/a-question-of-truth....

Another notable example is nonzero? which returns the value of the number if nonzero and nil otherwise:

  jruby-1.6.8 :097 > 1.nonzero?
   => 1 
  jruby-1.6.8 :098 > 0.nonzero?
   => nil 
See also File#world_writable? [1], File#world_readable? [2], File#size? [3], Kernel#autoload? [4], Encoding#compatible? [5]

If you rely on predicates always returning true/false you're in for a nasty surprise.

  [1] http://ruby-doc.org/core-1.9.3/File.html#method-c-world_writable-3F
  [2] http://ruby-doc.org/core-1.9.3/FileTest.html#method-i-world_readable-3F
  [3] http://ruby-doc.org/core-1.9.3/File.html#method-c-size-3F
  [4] http://ruby-doc.org/core-1.9.3/Kernel.html#method-i-autoload-3F 
  [5] http://ruby-doc.org/core-1.9.3/Encoding.html#method-c-compatible-3F


`defined?` is actually an operator: http://www.ruby-doc.org/docs/ProgrammingRuby/tut_expressions...

That may make things actually more confusing on first glance, but it does give a technical reason why it doesn't follow method naming conventions.


defined? behaves completely correct in respect to naming conventions. It's behavior is notable in a different way: It's one of the few places where undefined constants can appear in the code without raising an exception:

  jruby-1.6.8 :089 > defined? Foo::Bar
   => nil 
  jruby-1.6.8 :090 > Foo::Bar
  NameError: uninitialized constant Foo::Bar




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: