Ruby

Ruby

Made by DeepSource

rescue MethodError can be replaced with respond_to? RB-P1001

Performance
Minor

Rescuing NoMethodError can be upto 8x slower than checking for the method using respond_to?. rescue expects the exception to be raised first, hence it is much slower.

Bad practice

def slow
  begin
    writing
  rescue NoMethodError
    # Do something else...
  end
end

Recommended

def fast
  if respond_to?(:writing)
    writing
  else
    # Do something else...
  end
end

References

  1. (Benchmarking exceptions in Ruby - yep, they're slow.)[https://www.honeybadger.io/blog/benchmarking-exceptions-in-ruby-yep-theyre-slow/]
  2. (fast-ruby#recuevsrespondto)[https://github.com/fastruby/fast-ruby#beginrescue-vs-respondto-for-control-flow-code]