Browse files

Revert "don't raise NoMethodError the tried method doesn't exists"

This reverts commit 29a5aea.
  • Loading branch information...
1 parent 2e9e647 commit 82d41c969897cca28bb318f7caf301d520a2fbf3 @josevalim josevalim committed Oct 5, 2011
@@ -28,8 +28,6 @@ class Object
def try(*a, &b)
if a.empty? && block_given?
yield self
- elsif !a.empty? && !respond_to?(a.first)
- nil
__send__(*a, &b)
@@ -99,7 +99,7 @@ def setup
def test_nonexisting_method
method = :undefined_method
assert !@string.respond_to?(method)
- assert_nil @string.try(method)
+ assert_raise(NoMethodError) { @string.try(method) }
def test_nonexisting_method_with_arguments

8 comments on commit 82d41c9


Hooray! Welcome back, try!


It will broke some apps.

Maybe a deprecation warning before removing?


This was the behavior in 3.0.x and suddenly changed in 3.1.0. I am considering this a bug fix.


Please note two things :


@dmathieu they should be using respond_to?. obj.respond_to?(:product) ? obj.product : other using try in that code hides a lot of behavior. it hides the intent that obj can be something that is not nil and does not respond to product.

The behavior reverted in this commit was in fact the first version of try and it was changed a long, long time ago.


We were talking about that with @cesario today. Would something like try!(:product) ignoring the NoMethodError be something acceptable ?


Personally, I would never replace a obj.respond_to?(:product) ? obj.product : other by a obj.try!(:product) || other even if I have to type less. So I would vote no.


In the past, I've defined my own respond_to extension method that does what @dmathieu is talking about.

def respond_to(method, *args, &block)
  respond_to?(method) ? send(method, *args, &block) : nil

I don't use that anymore these days but if there's a call for it, I still like the respond_to naming.

Please sign in to comment.