Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are "begin" and "end" reserved words or not?

Tags:

ruby

I'm kind of confused about reserved words in Ruby.

"The Ruby Programming Language", co-authored by Matz, says that begin and end are reserved words of the language. They're certainly used syntactically to mark out blocks.

However, range objects in the language have methods named begin and end, as in

(1..10).end
=> 10 

Now, testing this out, I find that, indeed, I can define methods named "begin" and "end" on objects, though if I try to name a variable "begin" it fails. (Here's a sample of using it as a method name, it actually works...:)

class Foo
  def begin
    puts "hi"
  end
end

Foo.new.begin

So, I suppose I'm asking, what actually is the status of reserved words like this? I would have imagined that they couldn't be used for method names (and yet it seems to work) or that at the very least it would be terrible style (but it is actually used in the core language for the Range class).

I'm pretty confused as to when they're allowed to be used and for what. Is there even documentation on this?

like image 924
Perry Avatar asked Apr 06 '12 17:04

Perry


People also ask

What are reserved words examples?

1. Often found in programming languages and macros, reserved words are terms or phrases appropriated for special use that may not be utilized in the creation of variable names. For example, "print" is a reserved word because it is a function in many languages to show text on the screen.


1 Answers

Yes, they are reserved words. Yes, they can be used for method names. No, you can't call them without an explicit receiver. It's probably not a good idea anyway.

class Foo
  def if(foo)
    puts foo
  end
end

Foo.new.if("foo") # outputs foo, returns nil

Update: Here's a quote from "The Ruby Programming Language", by Matz (the creator of Ruby) himself:

In most languages, these words would be called “reserved words” and they would be never allowed as identifiers. The Ruby parser is flexible and does not complain if you prefix these keywords with @, @@, or $ prefixes and use them as instance, class, or global variable names. Also, you can use these keywords as method names, with the caveat that the method must always be explicitly invoked through an object.

like image 84
Michael Kohl Avatar answered Sep 27 '22 19:09

Michael Kohl