Jesse
Jesse

Reputation: 418

Is there any issues to have `end` as a method name?

I am working on a RoR project, and I want to know if I can use end as a method name. It seems to work fine, but I would like to know if this method will bring any issues in the future. I tried and it works:

class Dany
  def end
    puts 'Hola'
  end
end

and this is the output:

Dany.new.end # => Hola

Upvotes: 1

Views: 98

Answers (2)

Mulan
Mulan

Reputation: 135357

Ruby let's you do this, but you're going to run into all sorts of issues.

# end.rb
class Dany

  def end
    puts "Hola"
  end

  def other
    end  # should puts Hola
  end
end

Instead, you will get

end.rb:10: syntax error, unexpected keyword_end, expecting end-of-input


Bottom line: don't do this. Don't use any keywords as a method name.

Upvotes: 8

sawa
sawa

Reputation: 168199

It is not a good idea to use a keyword as a method name, but as long as you disambiguate the token as a method call, you can use it. It is not practical though.

Dany.new.instance_eval{self.end} # => Hola
Dany.new.send(:end)              # => Hola
Dany.new.method(:end).call       # => Hola
Dany.new.instance_eval{end}      # => syntax error, unexpected keyword_end

The usual disambiguation using () does not seem to work for this case, making it complicated.

Dany.new.instance_eval{end()}    # => syntax error, unexpected keyword_end

Upvotes: 3

Related Questions