Ruby `retry` keyword and name clash

Lets check out ruby snippet:

class A
  def retry_me
    puts 'retry me called'
    raise unless @r
  rescue
    @r = 1
    retry
  end
end

A.new.retry_me

It produces:

$ ruby retry.rb 
retry me called
retry me called

What happens if retry method gets added?

class A
  def retry
    puts 'retry called'
  end

  def retry_me
    puts 'retry me called'
    raise unless @r
  rescue
    @r = 1
    retry
  end
end

A.new.retry_me

Luckily, ruby is smart enough to remember that retry is a keyword, producing same result

$ ruby retry.rb 
retry me called
retry me called

In case you still want to have retry method you must call it via send(:retry) or with explicit receiver:

class A
  def retry
    puts 'retry called'
  end

  def retry_me
    puts 'retry me called'
    raise unless @r
  rescue
    @r = 1
    self.retry
  end
end

A.new.retry_me

Produces:

$ ruby retry.rb 
retry me called
retry called

It’s always a good idea to avoid use of reserved words for naming.

Read More
Vim doesnt' copy/paste from X11 clipboard
Building Ruby 1.8.6 with Openssl 1 on Arch
Comments
read or add one↓