What are the reserved words BEGIN or END used for in Ruby?
As all keywords BEGIN
and END
are documented as public instance methods of Object
(even though you won't see them returned from Object.public_instance_methods
)
BEGIN Designates, via code block, code to be executed unconditionally before sequential execution of the program begins.
Sometimes used to simulate forward references to methods.puts times_3(gets.to_i)
BEGIN {
def times_3(n)
n * 3
end
}
END Designates, via code block, code to be executed just prior to program termination.
END {
puts "Bye!"
}
Some more detailed explanation from Programming Ruby The Pragmatic Programmer's Guide
BEGIN and END Blocks
Every Ruby source file can declare blocks of code to be run as the
file is being loaded (the BEGIN blocks) and after the program has
finished executing (the END blocks).BEGIN {
begin code
}
END {
end code
}
A program may include multiple BEGIN and END blocks. BEGIN blocks are
executed in the order they are encountered. END blocks are executed in
reverse order.
Are begin and end reserved words or not?
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.
Subject a reserved word in Rails?
As you correctly say, SubjectsHelper is already provided by Social Stream. See:
https://github.com/ging/social_stream/blob/master/base/app/helpers/subjects_helper.rb
Your solution is working because you are reopening the module, which is a valid action in Ruby.
Built-in way to determine whether a string is a Ruby reserved word?
The only way I can think of is loading an array with all the keywords you know about.
class String
def is_keyword?
%w{__FILE__ __LINE__ alias and begin BEGIN break case class def defined? do else elsif end END ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield}.include? self
end
end
"foobar".is_keyword? # => false
"for".is_keyword? # => true
For reference:
- I know this isn't a built-in way, it's just the only way I could think of. Don't downvote me for it.
- The list I included is that of true keywords.
public
,protected
and friends aren't really keywords, just the names of important methods which are called during the creation of modules or classes. You can think of it as elements of the Ruby DSL.
Models with reserved keywords
This problem is addressed with modules:
Modules are a way of grouping together methods, classes, and
constants. Modules give you two major benefits:
- Modules provide a namespace and prevent name clashes.
- Modules implement the mixin facility.
[...]
Modules define a namespace, a sandbox in which your methods and
constants can play without having to worry about being stepped on by
other methods and constants.
In your case:
module MyRailsApp
class File
...
end
end
whereby your File
class is used as MyRailsApp::File
. This is the typical solution in Ruby, in Ruby on Rails this might be handled differently, please see the following references for an in depth discussion:
- Handling namespace models (classes) in namespace
- ActiveRecord: Can haz namespaces?
- Namespaced models and controllers
- Namespaced models
- A simple alternative to namespaced models
How can I create a list of reserved words in a Ruby program?
Well, you can always take a look at the ruby's source code: keywords.
Friendly_Id and Reserved Words -- How can i replace the reserved word?
Using the answers by daemonsy and SizzlePants I came up with this, which quietly renames "new" to "new2" and "edit" to "edit2", and keeps everything else as before:
class Page < ActiveRecord::Base
extend FriendlyId
friendly_id :friendly_id_title, use: :slugged
def friendly_id_title
case title.parameterize
when 'new' then 'new2'
when 'edit' then 'edit2'
else title
end
end
end
Ruby reserved class method names
You can always see a list of the methods implemented by default for every class:
class Try
end
t = Try.new
puts t.methods.sort
EDIT: actually you may also want to look at the private methods (where initialize
is):
puts t.private_methods.sort
Reserved names with ActiveRecord models
Reserved Word List
ADDITIONAL_LOAD_PATHS
ARGF
ARGV
ActionController
ActionView
ActiveRecord
ArgumentError
Array
BasicSocket
Benchmark
Bignum
Binding
CGI
CGIMethods
CROSS_COMPILING
Class
ClassInheritableAttributes
Comparable
ConditionVariable
Config
Continuation
DRb
DRbIdConv
DRbObject
DRbUndumped
Data
Date
DateTime
Delegater
Delegator
Digest
Dir
ENV
EOFError
ERB
Enumerable
Errno
Exception
FALSE
FalseClass
Fcntl
File
FileList
FileTask
FileTest
FileUtils
Fixnum
Float
FloatDomainError
GC
Gem
GetoptLong
Hash
IO
IOError
IPSocket
IPsocket
IndexError
Inflector
Integer
Interrupt
Kernel
LN_SUPPORTED
LoadError
LocalJumpError
Logger
Marshal
MatchData
MatchingData
Math
Method
Module
Mutex
Mysql
MysqlError
MysqlField
MysqlRes
NIL
NameError
NilClass
NoMemoryError
NoMethodError
NoWrite
NotImplementedError
Numeric
OPT_TABLE
Object
ObjectSpace
Observable
Observer
PGError
PGconn
PGlarge
PGresult
PLATFORM
PStore
ParseDate
Precision
Proc
Process
Queue
RAKEVERSION
RELEASE_DATE
RUBY
RUBY_PLATFORM
RUBY_RELEASE_DATE
RUBY_VERSION
Rack
Rake
RakeApp
RakeFileUtils
Range
RangeError
Rational
Regexp
RegexpError
Request
RuntimeError
STDERR
STDIN
STDOUT
ScanError
ScriptError
SecurityError
Signal
SignalException
SimpleDelegater
SimpleDelegator
Singleton
SizedQueue
Socket
SocketError
StandardError
String
StringScanner
Struct
Symbol
SyntaxError
SystemCallError
SystemExit
SystemStackError
TCPServer
TCPSocket
TCPserver
TCPsocket
TOPLEVEL_BINDING
TRUE
Task
Text
Thread
ThreadError
ThreadGroup
Time
Transaction
TrueClass
TypeError
UDPSocket
UDPsocket
UNIXServer
UNIXSocket
UNIXserver
UNIXsocket
UnboundMethod
Url
VERSION
Verbose
YAML
ZeroDivisionError
@base_path
accept
Acces
Axi
action
attributes
application2
callback
category
connection
database
dispatcher
display1
drive
errors
format
host
key
layout
load
link
new
notify
open
public
quote
render
request
records
responses
save
scope
send
session
system
template
test
timeout
to_s
type
URI
visits
Observer
Database Field Names
created_at
created_on
updated_at
updated_on
deleted_at
(paranoia
gem)
lock_version
type
id
#{table_name}_count
position
parent_id
lft
rgt
quote_value
Ruby Reserved Words
alias
and
BEGIN
begin
break
case
class
def
defined?
do
else
elsif
END
end
ensure
false
for
if
module
next
nil
not
or
redo
rescue
retry
return
self
super
then
true
undef
unless
until
when
while
yield
_ FILE _
_ LINE _
Related Topics
Rails How to Switch Between Dev and Production Mode
How to Apply a Patch to Ruby on Rails
How to Use Ruby Minitest::Spec with Rails for API Integration Tests
Post JSON Data to Simple Rails Application with Curl
What's the Most Efficient Way to Deep Copy an Object in Ruby
Ruby: Insert Spaces Every X Number of Characters
What Are the Reserved Words Begin or End Used for in Ruby
Rails Belongs_To Association (With :Class_Name) Returns Nil
Why Are Constants from Extended Module Not Available in Class Methods Declared with Self
How to Make Sign Up Page Be Root Page in Devise
How to Use Active Record Without Rails